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,4794 @@
1
+ """Lasso by coordinate descent over a Gram matrix, from Scheme via C++.
2
+
3
+ The solver is `examples/kernel-only/lasso-cov.scm` in the scm2cpp
4
+ repository, translated to C++ and compiled at install time. It takes
5
+ the covariance route: given X'X and X'y, each coordinate step costs
6
+ O(p) instead of O(n), so a whole regularization path is cheap once the
7
+ Gram matrix exists. The descent is exactly resumable, which is what
8
+ lets a path be walked warm and a batch of lambdas be handed to a GPU.
9
+
10
+ from scm2cpp_learn import CovLasso
11
+
12
+ model = CovLasso(X, y) # forms the Gram matrix
13
+ path = model.fit_path(lambdas) # warm, sequential
14
+ grid = model.fit_path_batch(lambdas) # cold, one thread each
15
+
16
+ `fit_path_batch` uses CUDA when the package was built with nvcc present
17
+ and a device is visible, and falls back to the CPU otherwise; ask
18
+ `cuda_available()` if you need to know which you got.
19
+
20
+ Designs with structure need not form X'X the general way. `kernel`
21
+ exposes the translated functions directly, and `scm2cpp-tfs` uses them
22
+ to build the Gram matrix of a moving-average design in O(n p) time and
23
+ no design matrix at all.
24
+ """
25
+ import ctypes
26
+ import os
27
+ import warnings
28
+
29
+ import numpy as np
30
+
31
+ from ._generated import _loader as kernel
32
+ from ._libfind import load_batch_lib, derived_backends, nmf_backends
33
+ from ._compat import (BaseEstimator, ClassifierMixin, RegressorMixin, TransformerMixin,
34
+ DensityMixin, Tagged, fit_xy, fit_x, pred_x, classes_of,
35
+ check_is_fitted, as_csr, _issparse)
36
+
37
+ # the derived kernel's variants that were built, each bound to its own
38
+ # library: {'cublas': module, 'blas': module, 'loops': module}
39
+ _DERIVED = {}
40
+ for _v in derived_backends():
41
+ try:
42
+ _DERIVED[_v] = __import__("scm2cpp_learn._generated._loader_derived_" + _v,
43
+ fromlist=["lasso"])
44
+ except ImportError:
45
+ pass
46
+
47
+ __all__ = ["GramLasso", "GramElasticNet", "GramRidge", "GramRidgeCV", "CovLasso", "CovRidge", "CovBayesianRidge", "CovLogistic", "CovGroupLasso",
48
+ "LinearSVM", "KernelSVM", "LinearSVR", "KernelSVR", "L1LogisticRegression",
49
+ "CDNMF", "nmf_backend", "CDGraphicalLasso", "LinearRANSAC",
50
+ "SGDLinearClassifier", "SGDLinearRegressor", "SGDPerceptron", "GramOMP", "GramLars", "GramLassoLars", "GramLassoLarsIC",
51
+ "LBFGSLogisticRegression", "LBFGSHuberRegressor", "LBFGSLogisticRegressionCV",
52
+ "LBFGSPoissonRegressor", "LBFGSGammaRegressor", "LBFGSTweedieRegressor",
53
+ "GramLarsCV", "GramLassoLarsCV", "GramOMPCV",
54
+ "EMGaussianMixture", "CovPCA", "GramKernelPCA", "GramLDA", "GramTruncatedSVD", "GramPLSRegression", "GramPLSCanonical", "GramCCA", "GramPLSSVD", "GramFactorAnalysis", "GramLinearRegression", "ParallelFastICA", "CovARDRegression",
55
+ "L1LinearSVM", "WeiszfeldTheilSen", "f_regression", "f_classif", "SelectKBest",
56
+ "SelectPercentile", "GramRFE",
57
+ "CovMultiTaskLasso", "CovMultiTaskLassoCV", "DerivedLasso",
58
+ "GramLogisticRegression", "GramGroupLasso", "GramMultiTaskLasso",
59
+ "GramMultiTaskElasticNet", "DesignLasso",
60
+ "cuda_available", "derived_backend", "kernel"]
61
+ __version__ = "0.22.0"
62
+
63
+ _BATCH = load_batch_lib()
64
+ _DP = ctypes.POINTER(ctypes.c_double)
65
+
66
+
67
+ def _scale(beta):
68
+ """What `tol` is measured against.
69
+
70
+ An absolute test on the coefficients is a trap when the features
71
+ are large: the Gram diagonal is then large too, every sweep moves
72
+ each coefficient by very little, and the descent declares victory
73
+ a long way from the solution. Measuring the move against the size
74
+ of the coefficients themselves makes the test mean the same thing
75
+ at any scale, and falls back to absolute when they are still near
76
+ zero.
77
+ """
78
+ m = float(np.max(np.abs(beta))) if beta.size else 0.0
79
+ return m if m > 1.0 else 1.0
80
+
81
+
82
+ def cuda_available():
83
+ """True when the GPU batch path was built and a device answers."""
84
+ if _BATCH is None:
85
+ return False
86
+ g, c, b = np.ones(1), np.zeros(1), np.zeros(1)
87
+ lam = np.array([1e9]) # a lambda that zeroes everything
88
+ return 0 == _BATCH.scm2cpp_batch_descend(
89
+ g.ctypes.data_as(_DP), 1, c.ctypes.data_as(_DP),
90
+ b.ctypes.data_as(_DP), lam.ctypes.data_as(_DP), 1.0, 1, 1, 1.0,
91
+ 20, 20, 1e-8)
92
+
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
+
154
+ class CovLasso:
155
+ """Lasso over a design given by its Gram matrix.
156
+
157
+ Either hand it the design and the target, in which case X'X and
158
+ X'y are formed here, or hand it a Gram matrix and correlations
159
+ somebody else built more cheaply.
160
+
161
+ Parameters
162
+ ----------
163
+ X : array (nobs, p), optional
164
+ The design matrix.
165
+ y : array (nobs,), optional
166
+ The target.
167
+ gram : array (p, p) or (p*p,), optional
168
+ X'X, if it is already known.
169
+ corr : array (p,), optional
170
+ X'y, likewise.
171
+ nobs : int, optional
172
+ Rows behind `gram`; required when passing one, since the
173
+ penalty is scaled by it as scikit-learn's alpha is.
174
+
175
+ The objective is the usual one, matching scikit-learn's `Lasso`
176
+ with `fit_intercept=False`:
177
+
178
+ (1 / 2 nobs) ||y - X b||^2 + lam ||b||_1
179
+ """
180
+
181
+ def __init__(self, X=None, y=None, *, gram=None, corr=None, nobs=None):
182
+ if gram is not None:
183
+ if corr is None or nobs is None:
184
+ raise ValueError("gram needs corr and nobs alongside it")
185
+ g = np.ascontiguousarray(gram, dtype=np.float64).ravel()
186
+ c = np.ascontiguousarray(corr, dtype=np.float64)
187
+ p = c.size
188
+ if g.size != p * p:
189
+ raise ValueError(f"gram is {g.size} entries; expected {p*p}")
190
+ self.p, self.nobs, self.g, self.c0 = p, int(nobs), g, c
191
+ else:
192
+ if X is None or y is None:
193
+ raise ValueError("pass X and y, or gram, corr and nobs")
194
+ X = np.ascontiguousarray(X, dtype=np.float64)
195
+ y = np.ascontiguousarray(y, dtype=np.float64)
196
+ if X.ndim != 2 or y.ndim != 1 or X.shape[0] != y.size:
197
+ raise ValueError(
198
+ f"X is {X.shape} and y is {y.shape}; expected (n, p) "
199
+ "and (n,)")
200
+ self.nobs, self.p = X.shape
201
+ self.g = np.ascontiguousarray((X.T @ X).ravel())
202
+ self.c0 = np.ascontiguousarray(X.T @ y)
203
+ self.X, self.y = X, y
204
+
205
+
206
+ # ------------------------- choosing lambdas -------------------------
207
+
208
+ def lambda_max(self, l1_ratio=1.0):
209
+ """The smallest penalty that leaves every coefficient at zero.
210
+
211
+ Above it the solution is exactly zero, so a path that starts
212
+ here starts where the first coefficient is about to enter --
213
+ which is the only scale-free place to start, since the penalty
214
+ is compared against correlations on the features' own scale.
215
+ """
216
+
217
+ return float(np.max(np.abs(self.c0))) / (self.nobs * l1_ratio)
218
+
219
+ def lambda_grid(self, num=100, eps=1e-3, l1_ratio=1.0):
220
+ """A log-spaced path from lambda_max down to eps * lambda_max.
221
+
222
+ The same construction scikit-learn uses, and the same default
223
+ ratio; give the result to fit_path, which expects descending
224
+ lambdas.
225
+ """
226
+ hi = self.lambda_max(l1_ratio)
227
+ return hi * np.logspace(0, np.log10(eps), int(num))
228
+
229
+ # ---------------------------- fitting ----------------------------
230
+
231
+ def fit(self, lam, **kw):
232
+ """Coefficients at one lambda.
233
+
234
+ A single penalty is the one-element special case of the path:
235
+ the Gram matrix was built in the constructor, so this costs one
236
+ descent and nothing per row -- and a warm-started path over a
237
+ whole grid costs barely more, which is why fit_path is the
238
+ primary interface rather than this convenience.
239
+ """
240
+ return self.fit_path([lam], **kw)[0]
241
+
242
+ def fit_path(self, lambdas, tol=1e-8, chunk=20, max_sweeps=100000,
243
+ l1_ratio=1.0):
244
+ """Coefficients per lambda, each warm-started from the last.
245
+
246
+ Returns an array of shape (len(lambdas), p). Give lambdas in
247
+ descending order: that is what makes the warm start pay.
248
+ """
249
+ lambdas = np.asarray(lambdas, dtype=np.float64)
250
+ beta, c = np.zeros(self.p), self.c0.copy()
251
+ prev = np.empty(self.p)
252
+ out = np.empty((lambdas.size, self.p))
253
+ for i, lam in enumerate(lambdas):
254
+ swept = 0
255
+ while swept < max_sweeps:
256
+ prev[:] = beta
257
+ kernel.enet_descend(self.g, c, beta,
258
+ float(lam) * l1_ratio,
259
+ float(lam) * (1.0 - l1_ratio), chunk,
260
+ float(self.nobs), self.p)
261
+ swept += chunk
262
+ if np.max(np.abs(beta - prev)) < tol * _scale(beta):
263
+ break
264
+ out[i] = beta
265
+ return out
266
+
267
+
268
+ def bootstrap(self, lam, n_boot=200, l1_ratio=1.0, seed=None,
269
+ force_cpu=False, **kw):
270
+ """Pairs-bootstrap coefficients at one lambda, (n_boot, p).
271
+
272
+ Each resample draws rows with replacement; its Gram matrix is
273
+ X' diag(m) X with the multiplicity counts m, formed as Xs' Xs
274
+ for Xs = diag(sqrt m) X so that numpy takes the symmetric
275
+ rank-k product (dsyrk, half the flops of a general product)
276
+ -- one BLAS call per resample -- and the descents run as one
277
+ batch: on the GPU one block of threads per resample over its
278
+ own Gram, since the problems are independent. Needs the
279
+ design matrix, so it is unavailable when the model was built
280
+ from a Gram matrix alone.
281
+ """
282
+ if not hasattr(self, "X"):
283
+ raise ValueError("bootstrap needs X; construct from X and y")
284
+ rng = np.random.default_rng(seed)
285
+ B = int(n_boot)
286
+ grams = np.empty((B, self.p * self.p))
287
+ corrs = np.empty((B, self.p))
288
+ for b in range(B):
289
+ m = rng.multinomial(self.nobs,
290
+ np.full(self.nobs, 1.0 / self.nobs))
291
+ Xs = self.X * np.sqrt(m)[:, None]
292
+ grams[b] = (Xs.T @ Xs).ravel()
293
+ corrs[b] = self.X.T @ (m * self.y)
294
+ lams = (np.ascontiguousarray(lam, dtype=np.float64)
295
+ if np.ndim(lam) else np.full(B, float(lam)))
296
+ if not force_cpu:
297
+ beta = _grid_descend(grams, corrs, lams, self.p, 0,
298
+ l1_ratio=l1_ratio, nobs=float(self.nobs),
299
+ **kw)
300
+ if beta is not None:
301
+ return beta
302
+ return _batch_descend_multi(grams, corrs, lams, self.nobs, self.p,
303
+ l1_ratio=l1_ratio, force_cpu=True,
304
+ kernel_fn=kernel.enet_descend, **kw)
305
+
306
+ def fit_path_batch(self, lambdas, tol=1e-8, chunk=20,
307
+ max_sweeps=100000, force_cpu=False, l1_ratio=1.0):
308
+ """Coefficients per lambda, every lambda solved from zero.
309
+
310
+ Independent problems, so they go to the GPU together when one
311
+ is available: one launch, one block of threads per lambda, all
312
+ sharing this Gram matrix. This is the shape of a
313
+ cross-validation grid, where warm starting across lambdas is
314
+ not on offer anyway.
315
+ """
316
+ lambdas = np.ascontiguousarray(lambdas, dtype=np.float64)
317
+ batch = lambdas.size
318
+ if not force_cpu:
319
+ beta = _grid_descend(self.g[None, :], self.c0[None, :], lambdas,
320
+ self.p, 0, tol=tol, chunk=chunk,
321
+ max_sweeps=max_sweeps, l1_ratio=l1_ratio,
322
+ nobs=float(self.nobs))
323
+ if beta is not None:
324
+ return beta
325
+ # a device that refused the work is not a reason to fail
326
+ beta = np.zeros((batch, self.p))
327
+ c = np.tile(self.c0, (batch, 1))
328
+ prev = np.empty(self.p)
329
+ for t in range(batch):
330
+ bt, ct, swept = beta[t], c[t], 0
331
+ while swept < max_sweeps:
332
+ prev[:] = bt
333
+ kernel.enet_descend(self.g, ct, bt,
334
+ float(lambdas[t]) * l1_ratio,
335
+ float(lambdas[t]) * (1.0 - l1_ratio), chunk,
336
+ float(self.nobs), self.p)
337
+ swept += chunk
338
+ if np.max(np.abs(bt - prev)) < tol * _scale(bt):
339
+ break
340
+ return beta
341
+
342
+
343
+ class DerivedLasso:
344
+ """Lasso from the design matrix, by the kernel the translator derived.
345
+
346
+ CovLasso above is the usable one: numpy forms the Gram matrix, a
347
+ hand-written sweep (lasso-cov.scm) runs over it, and cross-
348
+ validation, bootstrap and the GPU grid all feed that sweep their
349
+ own Gram matrices. This class exists to show the translator's
350
+ work instead. Its kernel is examples/kernel-only/lasso-design.scm
351
+ -- the residual-form coordinate descent, the algorithm inside
352
+ scikit-learn's Lasso(precompute=False), written as flat loops over
353
+ X as numpy holds it (n rows of p), the residual and the column
354
+ norms taken inside, no Gram matrix in sight -- translated with
355
+ --derive and --blas:
356
+ the translator raised the loops to the array algebra, replaced the
357
+ residual by the memo c = X'r kept current through a Gram matrix it
358
+ hoisted in front of the penalty path, folded the column norms into
359
+ that Gram's diagonal, folded the products into one dsyrk and two
360
+ dgemv calls, and put the result under (if (< p n) ..)
361
+ with the original sweep in the else branch -- scikit-learn's
362
+ precompute='auto' rule, derived. Nothing in it is written at the Gram level by hand, and numpy
363
+ prepares nothing: X and y go in as they are.
364
+
365
+ Three variants of the same derivation can be built: 'cublas'
366
+ (--derive --cublas: the products on the device, X uploaded once per
367
+ fit_path call), 'blas' (--derive --blas, CBLAS) and 'loops'
368
+ (--derive alone: the Gram a scalar loop nest, much slower on large
369
+ designs). backend=None takes the best one this machine built and
370
+ can run -- cublas only when a device answers -- and
371
+ derived_backend() says which that is; backend='blas' etc. insists.
372
+
373
+ The constructor only checks shapes and keeps X (C-contiguous, as
374
+ numpy makes it) and y; everything else happens inside fit_path.
375
+
376
+ Convergence is the kernel's: a sweep in which no coefficient moved
377
+ by more than tol (absolute) ends the fit at that lambda, max_sweeps
378
+ bounds it; tol=0.0 asks for the exact fixed point. Same objective
379
+ as CovLasso.
380
+ """
381
+
382
+ def __init__(self, X, y, backend=None):
383
+ if backend is None:
384
+ backend = derived_backend()
385
+ if backend is None:
386
+ raise ImportError(
387
+ "scm2cpp_learn: the derived kernel was not built; "
388
+ "reinstall the package (pip install --force-reinstall "
389
+ "scm2cpp-learn)")
390
+ elif backend not in _DERIVED:
391
+ raise ValueError(f"derived kernel backend {backend!r} is not built; "
392
+ f"built: {sorted(_DERIVED)}")
393
+ self.backend = backend
394
+ self._kernel = _DERIVED[backend]
395
+ X = np.ascontiguousarray(X, dtype=np.float64)
396
+ y = np.ascontiguousarray(y, dtype=np.float64)
397
+ if X.ndim != 2 or y.ndim != 1 or X.shape[0] != y.size:
398
+ raise ValueError(
399
+ f"X is {X.shape} and y is {y.shape}; expected (n, p) and (n,)")
400
+ self.nobs, self.p = X.shape
401
+ self.X, self.y = X, y
402
+ self._c0 = None
403
+
404
+ @property
405
+ def c0(self):
406
+ # X'y, needed only to place the penalty grid
407
+ if self._c0 is None:
408
+ self._c0 = self.X.T @ self.y
409
+ return self._c0
410
+
411
+ def lambda_max(self):
412
+ return float(np.max(np.abs(self.c0))) / self.nobs
413
+
414
+ def lambda_grid(self, num=100, eps=1e-3):
415
+ hi = self.lambda_max()
416
+ return hi * np.logspace(0, np.log10(eps), int(num))
417
+
418
+ def fit(self, lam, **kw):
419
+ return self.fit_path([lam], **kw)[0]
420
+
421
+ def fit_path(self, lambdas, tol=1e-8, max_sweeps=100000):
422
+ """Coefficients per lambda, warm-started, shape (len(lambdas), p).
423
+
424
+ One call into the derived kernel: it takes the residual and
425
+ the column norms (folded into the Gram's diagonal when p < n),
426
+ builds the Gram matrix, walks the penalties, and leaves the
427
+ coefficient at each in a row of the result. tol is the largest move of
428
+ one coefficient in a sweep below which that lambda is done. The
429
+ kernel's value, the sweeps run over the whole path, is kept as
430
+ n_iter_.
431
+ """
432
+ lams = np.ascontiguousarray(lambdas, dtype=np.float64).ravel()
433
+ beta = np.zeros(self.p)
434
+ resid = np.empty(self.nobs) # filled by the kernel from y
435
+ xnorm = np.empty(self.p) # the column norms, taken inside
436
+ betas = np.zeros(lams.size * self.p)
437
+ self.n_iter_ = int(self._kernel.lasso_design(
438
+ self.X, self.y, resid, xnorm, beta, lams, betas, int(max_sweeps), float(tol),
439
+ self.nobs, self.p, lams.size))
440
+ return betas.reshape(lams.size, self.p)
441
+
442
+
443
+ class DesignLasso(Tagged, RegressorMixin, BaseEstimator):
444
+ """scikit-learn's ``Lasso`` interface over DerivedLasso: fit(X, y)
445
+ centres the data when ``fit_intercept`` and runs the derived kernel
446
+ at one penalty ``alpha``, same objective as GramLasso. ``tol`` is
447
+ the kernel's (the largest absolute move of one coefficient in a
448
+ sweep), ``max_iter`` its sweep cap and ``backend`` DerivedLasso's.
449
+
450
+ Attributes after fit: coef_, intercept_, n_iter_ (the sweeps the
451
+ kernel ran), n_features_in_.
452
+ """
453
+
454
+ def __init__(self, alpha=1.0, *, fit_intercept=True, tol=1e-8, max_iter=100000,
455
+ backend=None):
456
+ self.alpha, self.fit_intercept, self.tol, self.max_iter = alpha, fit_intercept, tol, max_iter
457
+ self.backend = backend
458
+
459
+ def fit(self, X, y):
460
+ X, y = fit_xy(self, X, y)
461
+ Xc, yc, xm, ym = _centered(X, y, self.fit_intercept)
462
+ m = DerivedLasso(Xc, yc, backend=self.backend)
463
+ self.coef_ = m.fit(float(self.alpha), tol=float(self.tol), max_sweeps=int(self.max_iter))
464
+ self.n_iter_ = m.n_iter_
465
+ self.intercept_ = float(ym - xm @ self.coef_)
466
+ return self
467
+
468
+ def predict(self, X):
469
+ return pred_x(self, X) @ self.coef_ + self.intercept_
470
+
471
+
472
+ def derived_backend():
473
+ """The derived kernel variant DerivedLasso takes by default: 'cublas'
474
+ when built and a device answers, else 'blas', else 'loops'; None
475
+ when none was built."""
476
+ for v in ("cublas", "blas", "loops"):
477
+ if v in _DERIVED and (v != "cublas" or cuda_available()):
478
+ return v
479
+ return None
480
+
481
+
482
+ def _batch_descend_multi(grams, corrs, lam, nobs, p, tol=1e-8, chunk=20,
483
+ max_sweeps=100000, l1_ratio=1.0, force_cpu=False,
484
+ kernel_fn=None):
485
+ """Descend a batch where every problem has its own Gram matrix.
486
+
487
+ grams is (B, p*p) and corrs (B, p); one thread per problem on the
488
+ GPU when it is there (the kernel before 0.7.0, kept for the
489
+ comparison in bench/cv-grid-designs.py), the same chunked-tolerance
490
+ loop on the CPU when it is not -- which is what the bootstrap
491
+ falls back to.
492
+ """
493
+ B = corrs.shape[0]
494
+ import ctypes
495
+ beta = np.zeros((B, p))
496
+ c = np.ascontiguousarray(corrs.copy())
497
+ g = np.ascontiguousarray(grams)
498
+ # lam may be one penalty for every thread or one per thread; the
499
+ # kernel always reads a per-thread array
500
+ lams = (np.ascontiguousarray(lam, dtype=np.float64)
501
+ if np.ndim(lam) else np.full(B, float(lam)))
502
+ if _BATCH is not None and not force_cpu:
503
+ dp = ctypes.POINTER(ctypes.c_double)
504
+ rc = _BATCH.scm2cpp_batch_descend(
505
+ g.ctypes.data_as(dp), int(B), c.ctypes.data_as(dp),
506
+ beta.ctypes.data_as(dp), lams.ctypes.data_as(dp),
507
+ float(l1_ratio), int(B), int(p), float(nobs),
508
+ int(max_sweeps), int(chunk), float(tol))
509
+ if rc == 0:
510
+ return beta
511
+ prev = np.empty(p)
512
+ for b in range(B):
513
+ gb, cb, bb = g[b], c[b], beta[b]
514
+ lam_b = float(lams[b])
515
+ swept = 0
516
+ while swept < max_sweeps:
517
+ prev[:] = bb
518
+ kernel_fn(gb, cb, bb, lam_b * l1_ratio,
519
+ lam_b * (1.0 - l1_ratio), chunk,
520
+ float(nobs), p)
521
+ swept += chunk
522
+ if np.max(np.abs(bb - prev)) < tol * max(
523
+ 1.0, float(np.max(np.abs(bb)))):
524
+ break
525
+ return beta
526
+
527
+
528
+ def _grid_descend(grams, corrs, lams, p, ntask, tol=1e-8, chunk=20,
529
+ max_sweeps=100000, l1_ratio=1.0, nobs=1.0):
530
+ """A batch of cold descents on the GPU, one block per problem.
531
+
532
+ grams is (n_grams, p*p), corrs (n_grams, width) with width p or
533
+ p*ntask, and lams the penalties of the batch in Gram-major order:
534
+ problem i uses Gram i // (batch // n_grams). Every problem starts
535
+ from zero and nothing is replicated: a cross-validation grid of cv
536
+ folds by num penalties moves cv Gram matrices, a fit_path_batch
537
+ one, a bootstrap one per resample. Returns (batch, width), or
538
+ None when the GPU path is not there or declined the shape, in
539
+ which case the caller runs its CPU path.
540
+ """
541
+ fn = getattr(_BATCH, "scm2cpp_cv_descend", None) if _BATCH else None
542
+ if fn is None:
543
+ return None
544
+ n_grams, batch = corrs.shape[0], lams.size
545
+ if batch % n_grams:
546
+ return None
547
+ width = p * (ntask if ntask > 0 else 1)
548
+ g = np.ascontiguousarray(grams, dtype=np.float64)
549
+ c = np.ascontiguousarray(np.repeat(corrs, batch // n_grams, axis=0),
550
+ dtype=np.float64)
551
+ w = np.zeros((batch, width))
552
+ lams = np.ascontiguousarray(lams, dtype=np.float64)
553
+ rc = fn(g.ctypes.data_as(_DP), int(n_grams), c.ctypes.data_as(_DP),
554
+ w.ctypes.data_as(_DP), lams.ctypes.data_as(_DP),
555
+ float(l1_ratio), int(batch), int(p), int(ntask), float(nobs),
556
+ int(max_sweeps), int(chunk), float(tol), 1, 1)
557
+ return w if rc == 0 else None
558
+
559
+
560
+ class CovLassoCV(Tagged, RegressorMixin, BaseEstimator):
561
+ """Cross-validated lasso, scikit-learn's LassoCV semantics.
562
+
563
+ The lambda grid comes from the full data (lambda_max down, the
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
584
+ zero -- is one launch with one block of threads per problem, the
585
+ fold's Gram matrix shared by its problems; on the CPU each fold's
586
+ path is walked warm. force_cpu picks the CPU path; force_gpu is
587
+ accepted for compatibility (the GPU is now taken whenever it is
588
+ there and force_cpu is not set).
589
+
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
+ 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
+
616
+ Attributes after fit: alphas_, mse_path_ (num, n_folds), alpha_,
617
+ coef_, intercept_; with solver="lars" also n_polished_ and n_iter_ (the refit's
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.
620
+ """
621
+
622
+ def __init__(self, cv=5, num=100, eps=1e-3, tol=1e-8, l1_ratio=1.0,
623
+ force_cpu=False, force_gpu=False, n_jobs=1, fit_intercept=False,
624
+ solver="cd", working_set=None):
625
+ # Folds are independent, the descent is a ctypes call and the
626
+ # products are BLAS calls, both of which release the GIL, so
627
+ # plain threads scale the CPU path across folds. Default 1:
628
+ # sequential, like scikit-learn's n_jobs=None.
629
+ self.cv, self.num, self.eps, self.tol = cv, num, eps, tol
630
+ self.l1_ratio, self.force_cpu, self.force_gpu = l1_ratio, force_cpu, force_gpu
631
+ self.n_jobs, self.fit_intercept = n_jobs, fit_intercept
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
732
+
733
+ def _lars_grid(self, G, c, nobs):
734
+ """The lasso solutions at alphas_ (rows) for Gram G and
735
+ correlations c, by the translated LARS path interpolated on the
736
+ grid; also the number of path steps.
737
+
738
+ Columns equal up to a factor (|correlation| > 1 - 1e-10) are cut
739
+ to the one of largest norm first: the lasso puts the whole
740
+ weight of such a group on that column anyway, and two equal
741
+ columns tie in LARS's correlations and break its Cholesky
742
+ updates. The path is rerun with twice the steps while it stops
743
+ short of the grid's end. A grid point whose solution still
744
+ misses the optimality conditions (|gradient| <= alpha, equal on
745
+ the support, to 1e-5 relative) is finished by coordinate
746
+ descent from it."""
747
+ p = c.shape[0]
748
+ G = np.array(G, dtype=np.float64).reshape(p, p)
749
+ c = np.array(c, dtype=np.float64)
750
+ alphas = self.alphas_
751
+ keep = _dedup_columns(G)
752
+ out = np.zeros((len(alphas), p))
753
+ it = 0
754
+ if keep.size:
755
+ q = keep.size
756
+ Gk = np.ascontiguousarray(G[np.ix_(keep, keep)])
757
+ # the path's stopping test compares alpha with an absolute
758
+ # 1.2e-7 (scikit-learn's): solve with the correlations scaled
759
+ # so that the largest alpha is 1 (coefficients and alphas
760
+ # scale with them), and run to just below the grid's end
761
+ sc = float(np.max(np.abs(c[keep]))) / float(nobs)
762
+ sc = sc if sc > 0 else 1.0
763
+ amin = 0.999 * float(alphas[-1]) / sc
764
+ maxiter = 2 * min(int(nobs), q) + 100
765
+ while True:
766
+ path = np.zeros((maxiter + 1, q))
767
+ knots = np.zeros(maxiter + 1)
768
+ it = _classifier_kernels().lars(
769
+ Gk.copy(), c[keep] / sc, np.zeros(q), path, knots, 1, float(nobs),
770
+ amin, 1, maxiter, float(np.finfo(np.float64).eps), q)
771
+ if it < maxiter or knots[it] <= amin or maxiter > 64 * q + 1000:
772
+ break
773
+ maxiter *= 2
774
+ al, coefs = knots[:it + 1] * sc, path[:it + 1] * sc
775
+ # knots descend; grid point a lies between knots k-1 and k
776
+ k = np.searchsorted(-al, -alphas)
777
+ sub = np.empty((len(alphas), q))
778
+ lo = k == 0
779
+ hi = k >= len(al)
780
+ mid = ~(lo | hi)
781
+ sub[lo] = coefs[0]
782
+ sub[hi] = coefs[-1]
783
+ km = k[mid]
784
+ t = (al[km - 1] - alphas[mid]) / (al[km - 1] - al[km])
785
+ sub[mid] = coefs[km - 1] + t[:, None] * (coefs[km] - coefs[km - 1])
786
+ out[:, keep] = sub
787
+ self._lars_polished_ = getattr(self, "_lars_polished_", 0) + _polish_lasso(
788
+ G, c, float(nobs), alphas, out, self.tol)
789
+ return out, int(it)
790
+
791
+ def _folds(self, X, y, n):
792
+ """[(train, test)] with train None when it is test's complement;
793
+ test (and a non-None train) is an index array or a slice."""
794
+ if isinstance(self.cv, (int, np.integer)):
795
+ # contiguous folds in row order, sizes as even as they come --
796
+ # sklearn's KFold(shuffle=False)
797
+ bounds = np.linspace(0, n, int(self.cv) + 1).astype(int)
798
+ return [(None, slice(lo, hi)) for lo, hi in zip(bounds[:-1], bounds[1:])]
799
+ splits = self.cv.split(X, y) if hasattr(self.cv, "split") else self.cv
800
+ folds = []
801
+ for tr, te in splits:
802
+ tr, te = np.asarray(tr, dtype=np.intp), np.asarray(te, dtype=np.intp)
803
+ seen = np.zeros(n, dtype=bool)
804
+ seen[tr] = True
805
+ if tr.size + te.size == n and not seen[te].any() and seen.sum() == tr.size:
806
+ folds.append((None, te))
807
+ elif tr.size and tr[0] == 0 and tr[-1] == tr.size - 1 and np.all(np.diff(tr) == 1):
808
+ folds.append((slice(0, tr.size), te))
809
+ else:
810
+ folds.append((tr, te))
811
+ if not folds:
812
+ raise ValueError("cv produced no folds")
813
+ return folds
814
+
815
+ def _fold_stats(self, X, y, n, raw, train, test, prefix):
816
+ """(Gram, correlations, nobs, x mean, y mean) of a fold's training
817
+ rows, centred when fit_intercept. prefix is [rows, G, c, sx, sy]
818
+ of the last prefix formed, advanced in place."""
819
+ G, c0 = raw.g.reshape(raw.p, raw.p), raw.c0
820
+ if train is None:
821
+ Xf, yf = X[test], y[test]
822
+ Gt, ct = G - Xf.T @ Xf, c0 - Xf.T @ yf
823
+ nt = n - yf.shape[0]
824
+ sx, sy = self._sx - Xf.sum(axis=0), self._sy - yf.sum()
825
+ elif isinstance(train, slice):
826
+ # growing prefixes: add the rows since the last one
827
+ a, b = prefix[0], train.stop
828
+ if b < a:
829
+ prefix[:] = [0, np.zeros_like(G), np.zeros_like(c0), np.zeros(raw.p), 0.0]
830
+ a = 0
831
+ Xd, yd = X[a:b], y[a:b]
832
+ prefix[1] = prefix[1] + Xd.T @ Xd
833
+ prefix[2] = prefix[2] + Xd.T @ yd
834
+ prefix[3] = prefix[3] + Xd.sum(axis=0)
835
+ prefix[4] = prefix[4] + yd.sum()
836
+ prefix[0] = b
837
+ Gt, ct, nt, sx, sy = prefix[1].copy(), prefix[2].copy(), b, prefix[3], prefix[4]
838
+ else:
839
+ Xt, yt = X[train], y[train]
840
+ Gt, ct, nt = Xt.T @ Xt, Xt.T @ yt, yt.shape[0]
841
+ sx, sy = Xt.sum(axis=0), yt.sum()
842
+ if not self.fit_intercept:
843
+ return Gt, ct, nt, np.zeros(raw.p), 0.0
844
+ xm, ym = sx / nt, sy / nt
845
+ nm2 = nt * xm * xm
846
+ if np.all(np.diagonal(Gt) - nm2 > 1e-4 * nm2):
847
+ Gt -= np.outer(xm, nt * xm)
848
+ ct -= nt * xm * ym
849
+ else:
850
+ # a column whose mean dwarfs its spread: the correction would
851
+ # cancel its digits (see _centered_gram), so centre the rows
852
+ if train is None:
853
+ keep = np.ones(n, dtype=bool)
854
+ keep[test] = False
855
+ Xt, yt = X[keep], y[keep]
856
+ else:
857
+ Xt, yt = X[train], y[train]
858
+ Xc = Xt - xm
859
+ Gt, ct = Xc.T @ Xc, Xc.T @ (yt - ym)
860
+ return Gt, ct, nt, xm, ym
861
+
862
+ def fit(self, X, y):
863
+ X, y = fit_xy(self, X, y)
864
+ if self.working_set is not None:
865
+ return self._fit_working_set(X, y)
866
+ n = len(y)
867
+ num = int(self.num)
868
+ tol, l1_ratio = float(self.tol), float(self.l1_ratio)
869
+ raw = CovLasso(X, y)
870
+ self._sx, self._sy = X.sum(axis=0), float(y.sum())
871
+ if self.fit_intercept:
872
+ G, c, xm, ym = _centered_gram(X, y, True)
873
+ full = CovLasso(gram=G, corr=c, nobs=n)
874
+ self._xm, self._ym = xm, float(ym)
875
+ else:
876
+ full = raw
877
+ self._xm, self._ym = np.zeros(X.shape[1]), 0.0
878
+ self.alphas_ = full.lambda_grid(num=num, eps=float(self.eps),
879
+ l1_ratio=l1_ratio)
880
+ folds = self._folds(X, y, n)
881
+ self.mse_path_ = np.empty((num, len(folds)))
882
+ if self.solver not in ("cd", "lars"):
883
+ raise ValueError(f"solver must be 'cd' or 'lars', got {self.solver!r}")
884
+ lars = self.solver == "lars"
885
+ self._lars_polished_ = 0
886
+ if lars and l1_ratio != 1.0:
887
+ raise ValueError("solver='lars' solves the lasso only (l1_ratio=1)")
888
+ self._full = full
889
+ if cuda_available() and not self.force_cpu and not lars:
890
+ done = self._fit_gpu(X, y, raw, full, folds, n)
891
+ if done is not None:
892
+ return done
893
+
894
+ prefix = [0, np.zeros((raw.p, raw.p)), np.zeros(raw.p), np.zeros(raw.p), 0.0]
895
+
896
+ def one_fold(k, stats=None):
897
+ train, test = folds[k]
898
+ Gt, ct, nt, xm, ym = stats or self._fold_stats(X, y, n, raw, train, test, prefix)
899
+ m = CovLasso(gram=Gt.ravel(), corr=ct, nobs=nt)
900
+ # The warm-started path: after the Gram, each lambda resumes
901
+ # where the previous stopped and costs O(p) per moving
902
+ # coordinate. That warm path is what makes searching the
903
+ # alpha grid cheap -- the grid costs barely more than its
904
+ # hardest single alpha.
905
+ if lars:
906
+ path, _ = self._lars_grid(Gt, ct, nt)
907
+ else:
908
+ path = m.fit_path(self.alphas_, tol=tol, l1_ratio=l1_ratio)
909
+ resid = (X[test] - xm) @ path.T - (y[test] - ym)[:, None]
910
+ self.mse_path_[:, k] = np.mean(resid * resid, axis=0)
911
+
912
+ if int(self.n_jobs) > 1:
913
+ from concurrent.futures import ThreadPoolExecutor
914
+ # a prefix sum runs in fold order, so a prefix fold's statistics
915
+ # are formed here and only the descents run in the threads
916
+ pre = {k: self._fold_stats(X, y, n, raw, *folds[k], prefix)
917
+ for k in range(len(folds)) if isinstance(folds[k][0], slice)}
918
+ with ThreadPoolExecutor(max_workers=int(self.n_jobs)) as ex:
919
+ list(ex.map(lambda k: one_fold(k, pre.get(k)), range(len(folds))))
920
+ else:
921
+ for k in range(len(folds)):
922
+ one_fold(k)
923
+ return self._finish(full)
924
+
925
+ def _fit_gpu(self, X, y, raw, full, folds, n):
926
+ # Every fold and every alpha is an independent problem, so all of
927
+ # them go to the device as one batch, one block per problem,
928
+ # the problems of a fold sharing its Gram on the device. Fold
929
+ # sizes may differ; the kernel only ever uses lam through the
930
+ # product lam * nobs, so each problem's nobs is absorbed into its
931
+ # lambda and nobs is passed as 1 -- exact, not approximate.
932
+ # Returns None when the device declined, and the CPU path takes
933
+ # over.
934
+ p_ = full.p
935
+ num, nf = int(self.num), len(folds)
936
+ grams = np.empty((nf, p_ * p_))
937
+ corrs = np.empty((nf, p_))
938
+ nobs_k = np.empty(nf)
939
+ means = []
940
+ prefix = [0, np.zeros((p_, p_)), np.zeros(p_), np.zeros(p_), 0.0]
941
+ for k, (train, test) in enumerate(folds):
942
+ Gt, ct, nt, xm, ym = self._fold_stats(X, y, n, raw, train, test, prefix)
943
+ grams[k], corrs[k], nobs_k[k] = Gt.ravel(), ct, nt
944
+ means.append((xm, ym))
945
+ lams = (np.tile(self.alphas_, nf) * np.repeat(nobs_k, num))
946
+ betas = _grid_descend(grams, corrs, lams, p_, 0, tol=float(self.tol),
947
+ l1_ratio=float(self.l1_ratio))
948
+ if betas is None:
949
+ return None
950
+ betas = betas.reshape(nf, num, p_)
951
+ for k, (train, test) in enumerate(folds):
952
+ xm, ym = means[k]
953
+ resid = (X[test] - xm) @ betas[k].T - (y[test] - ym)[:, None]
954
+ self.mse_path_[:, k] = np.mean(resid * resid, axis=0)
955
+ return self._finish(full)
956
+
957
+ def _finish(self, full):
958
+ mean = self.mse_path_.mean(axis=1)
959
+ # alphas_ descends, so argmin's first hit is the larger penalty
960
+ ib = int(np.argmin(mean))
961
+ self.alpha_ = float(self.alphas_[ib])
962
+ if self.solver == "lars":
963
+ path, self.n_iter_ = self._lars_grid(full.g.reshape(full.p, full.p), full.c0,
964
+ full.nobs)
965
+ self.coef_ = path[ib].copy()
966
+ self.n_polished_ = self._lars_polished_
967
+ else:
968
+ self.coef_ = full.fit(self.alpha_, tol=float(self.tol),
969
+ l1_ratio=float(self.l1_ratio))
970
+ self.intercept_ = self._ym - float(self._xm @ self.coef_)
971
+ del self._sx, self._sy, self._xm, self._ym, self._full
972
+ return self
973
+
974
+ def predict(self, X):
975
+ return pred_x(self, X) @ self.coef_ + self.intercept_
976
+
977
+
978
+ class CovRidge:
979
+ """Ridge regression over a design given by its Gram matrix.
980
+
981
+ The objective matches scikit-learn's ``Ridge`` with
982
+ ``fit_intercept=False``:
983
+
984
+ ||y - X b||^2 + alpha ||b||^2
985
+
986
+ (note: unlike the lasso objective, scikit-learn does not scale this
987
+ one by the number of rows), so the solution is
988
+ ``b = (X'X + alpha I)^{-1} X'y``.
989
+
990
+ The design matrix enters only through X'X and X'y, so the
991
+ constructor takes either the design or a Gram matrix somebody built
992
+ more cheaply. One symmetric eigendecomposition is done on first
993
+ use, O(p^3); every alpha after that costs O(p^2), which is what
994
+ makes a whole path cheap.
995
+ """
996
+
997
+ def __init__(self, X=None, y=None, *, gram=None, corr=None):
998
+ if gram is not None:
999
+ if corr is None:
1000
+ raise ValueError("gram needs corr alongside it")
1001
+ g = np.ascontiguousarray(gram, dtype=np.float64).ravel()
1002
+ c = np.ascontiguousarray(corr, dtype=np.float64)
1003
+ p = c.size
1004
+ if g.size != p * p:
1005
+ raise ValueError(f"gram is {g.size} entries; expected {p*p}")
1006
+ self.p, self.g, self.c0 = p, g, c
1007
+ else:
1008
+ if X is None or y is None:
1009
+ raise ValueError("pass X and y, or gram and corr")
1010
+ X = np.ascontiguousarray(X, dtype=np.float64)
1011
+ y = np.ascontiguousarray(y, dtype=np.float64)
1012
+ if X.ndim != 2 or y.ndim != 1 or X.shape[0] != y.size:
1013
+ raise ValueError(
1014
+ f"X is {X.shape} and y is {y.shape}; expected (n, p) "
1015
+ "and (n,)")
1016
+ self.p = X.shape[1]
1017
+ self.g = np.ascontiguousarray(_gram(X).ravel())
1018
+ self.c0 = np.ascontiguousarray(_gram_xy(X, y))
1019
+ self._eig = None
1020
+
1021
+ def _eigen(self):
1022
+ if self._eig is None:
1023
+ w, Q = np.linalg.eigh(self.g.reshape(self.p, self.p))
1024
+ self._eig = (w, Q, Q.T @ self.c0)
1025
+ return self._eig
1026
+
1027
+ def alpha_grid(self, num=100, eps=1e-6):
1028
+ """A log-spaced path from the top eigenvalue of X'X downward.
1029
+
1030
+ At ``alpha`` around the largest eigenvalue the fit is heavily
1031
+ shrunk; by ``eps`` times it the fit is essentially least
1032
+ squares. Descending, like the lasso grids.
1033
+ """
1034
+ w, _, _ = self._eigen()
1035
+ hi = float(w.max())
1036
+ return hi * np.logspace(0, np.log10(eps), int(num))
1037
+
1038
+ def fit(self, alpha):
1039
+ """Coefficients at one alpha: one solve of X'X + alpha I while no
1040
+ path has needed the eigendecomposition (at p = 200 a few
1041
+ milliseconds against eigh's tenth of a second), through it after."""
1042
+ if self._eig is None and float(alpha) > 0.0:
1043
+ b = _ridge_solve(self.g.reshape(self.p, self.p), self.c0, float(alpha))
1044
+ if b is not None:
1045
+ return b
1046
+ w, Q, qc = self._eigen()
1047
+ return Q @ (qc / (w + float(alpha)))
1048
+
1049
+ def fit_path(self, alphas):
1050
+ """Coefficients per alpha, shape (len(alphas), p).
1051
+
1052
+ After the one eigendecomposition this is a single dense
1053
+ product, so thousands of alphas cost what one does.
1054
+ """
1055
+ w, Q, qc = self._eigen()
1056
+ alphas = np.asarray(alphas, dtype=np.float64)
1057
+ return (Q @ (qc[:, None] / (w[:, None] + alphas[None, :]))).T
1058
+
1059
+
1060
+ def _centered(X, y, fit_intercept):
1061
+ # the data the intercept-free solvers see: centred when an intercept
1062
+ # is fitted (scikit-learn's _preprocess_data), as they are otherwise
1063
+ if not fit_intercept:
1064
+ return X, y, np.zeros(X.shape[1]), np.zeros(y.shape[1:]) if y.ndim > 1 else 0.0
1065
+ xm, ym = X.mean(axis=0), y.mean(axis=0)
1066
+ return np.ascontiguousarray(X - xm), y - ym, xm, ym
1067
+
1068
+
1069
+ def _centered_gram(X, y, fit_intercept):
1070
+ """(Xc'Xc, Xc'yc, xm, ym) for the centred data Xc, yc, without
1071
+ forming Xc: X'X - n xm xm' and X'y - n xm ym, which saves the copy
1072
+ of X (as long as the Gram product itself on 20000 x 200 rows, where
1073
+ it took the intercept from free to twice the fit). The correction
1074
+ cancels digits when a column's mean is large against its spread,
1075
+ about (mean / sd)^2 ulps, so a column with mean over 100 sd (or no
1076
+ spread at all) sends the whole fit through the centred copy. A
1077
+ sparse X (CSR) takes the correction always -- centring would fill
1078
+ it in -- with X'X by csr-gram and X'y by csr-mm."""
1079
+ n = X.shape[0]
1080
+ if _issparse(X):
1081
+ G, c = _sparse_gram(X), _dot(X, y, transpose=True)
1082
+ if not fit_intercept:
1083
+ return G, c, np.zeros(X.shape[1]), np.zeros(y.shape[1:]) if y.ndim > 1 else 0.0
1084
+ xm, ym = _sparse_mean(X), y.mean(axis=0)
1085
+ G -= np.outer(xm, n * xm)
1086
+ c -= np.multiply.outer(n * xm, ym)
1087
+ return G, c, xm, ym
1088
+ G, c = _gram(X), _gram_xy(X, y)
1089
+ if not fit_intercept:
1090
+ return G, c, np.zeros(X.shape[1]), np.zeros(y.shape[1:]) if y.ndim > 1 else 0.0
1091
+ xm, ym = X.mean(axis=0), y.mean(axis=0)
1092
+ nm2 = n * xm * xm
1093
+ if np.all(np.diagonal(G) - nm2 > 1e-4 * nm2):
1094
+ G -= np.outer(xm, n * xm)
1095
+ c -= np.multiply.outer(n * xm, ym)
1096
+ return G, c, xm, ym
1097
+ Xc, yc = np.ascontiguousarray(X - xm), y - ym
1098
+ return Xc.T @ Xc, Xc.T @ yc, xm, ym
1099
+
1100
+
1101
+ class GramElasticNet(Tagged, RegressorMixin, BaseEstimator):
1102
+ """scikit-learn's ``ElasticNet(precompute=True)`` interface over
1103
+ CovLasso: fit(X, y) centres the data when ``fit_intercept``, forms
1104
+ the Gram matrix once and runs the covariance sweep at ``alpha``,
1105
+
1106
+ (1 / 2 n) ||y - X b - b0||^2 + alpha l1_ratio ||b||_1
1107
+ + (alpha / 2)(1 - l1_ratio) ||b||^2.
1108
+
1109
+ ``tol`` is CovLasso's (the largest coefficient move in a sweep,
1110
+ relative to the coefficients' size) and ``max_iter`` its sweep cap.
1111
+ For a whole path or a grid, CovLasso itself (fit_path,
1112
+ fit_path_batch) is the faster interface.
1113
+
1114
+ A scipy.sparse X is taken: X'X by csr-gram, its intercept by the
1115
+ n xm xm' correction (as scikit-learn's sparse coordinate descent
1116
+ keeps X uncentred too).
1117
+
1118
+ Attributes after fit: coef_, intercept_, n_features_in_.
1119
+ """
1120
+ _sparse = True
1121
+
1122
+ def __init__(self, alpha=1.0, *, l1_ratio=0.5, fit_intercept=True, tol=1e-8,
1123
+ max_iter=100000):
1124
+ self.alpha, self.l1_ratio, self.fit_intercept = alpha, l1_ratio, fit_intercept
1125
+ self.tol, self.max_iter = tol, max_iter
1126
+
1127
+ def fit(self, X, y):
1128
+ X, y = fit_xy(self, X, y)
1129
+ n, p = X.shape
1130
+ G, c, xm, ym = _centered_gram(X, y, self.fit_intercept)
1131
+ g = np.ascontiguousarray(G.ravel())
1132
+ c = np.ascontiguousarray(c)
1133
+ lam, r = float(self.alpha), float(self.l1_ratio)
1134
+ tol, cap = float(self.tol), int(self.max_iter)
1135
+ beta, prev = np.zeros(p), np.empty(p)
1136
+ swept = 0
1137
+ # CovLasso.fit_path's loop at one lambda, counting the sweeps
1138
+ while swept < cap:
1139
+ chunk = min(20, cap - swept)
1140
+ prev[:] = beta
1141
+ kernel.enet_descend(g, c, beta, lam * r, lam * (1.0 - r), chunk, float(n), p)
1142
+ swept += chunk
1143
+ if np.max(np.abs(beta - prev)) < tol * _scale(beta):
1144
+ break
1145
+ self.coef_, self.n_iter_ = beta, swept
1146
+ self.intercept_ = float(ym - xm @ self.coef_)
1147
+ return self
1148
+
1149
+ def predict(self, X):
1150
+ X = pred_x(self, X)
1151
+ return (_dot(X, self.coef_) if _issparse(X) else X @ self.coef_) + self.intercept_
1152
+
1153
+
1154
+ class GramLasso(GramElasticNet):
1155
+ """scikit-learn's ``Lasso(precompute=True)`` interface over CovLasso:
1156
+ GramElasticNet with l1_ratio 1.
1157
+
1158
+ Attributes after fit: coef_, intercept_, n_features_in_.
1159
+ """
1160
+
1161
+ def __init__(self, alpha=1.0, *, fit_intercept=True, tol=1e-8, max_iter=100000):
1162
+ self.alpha, self.fit_intercept, self.tol, self.max_iter = alpha, fit_intercept, tol, max_iter
1163
+
1164
+ @property
1165
+ def l1_ratio(self):
1166
+ return 1.0
1167
+
1168
+
1169
+ class GramRidge(Tagged, RegressorMixin, BaseEstimator):
1170
+ """scikit-learn's ``Ridge`` interface over the Gram matrix:
1171
+ (X'X + alpha I) b = X'y on the centred data by one Cholesky solve
1172
+ (least squares when alpha is 0 and X'X singular), y one target or
1173
+ several (coef_ then (n_targets, p), as Ridge has it). For many
1174
+ alphas, CovRidge's fit_path is the faster interface. A scipy.sparse
1175
+ X is taken (csr-gram, the intercept by the n xm xm' correction).
1176
+
1177
+ Attributes after fit: coef_, intercept_, n_features_in_.
1178
+ """
1179
+ _multi_output = True
1180
+ _sparse = True
1181
+
1182
+ def __init__(self, alpha=1.0, *, fit_intercept=True):
1183
+ self.alpha, self.fit_intercept = alpha, fit_intercept
1184
+
1185
+ def fit(self, X, y):
1186
+ X, y = fit_xy(self, X, y, multi_output=True)
1187
+ p = X.shape[1]
1188
+ A, b, xm, ym = _centered_gram(X, y, self.fit_intercept)
1189
+ coef = _ridge_solve(A, b, float(self.alpha))
1190
+ if coef is None:
1191
+ A.flat[::p + 1] += float(self.alpha)
1192
+ try:
1193
+ coef = np.linalg.solve(A, b)
1194
+ except np.linalg.LinAlgError:
1195
+ coef = np.linalg.lstsq(A, b, rcond=None)[0]
1196
+ self.coef_ = coef.T if coef.ndim > 1 else coef
1197
+ self.intercept_ = ym - xm @ coef
1198
+ if np.ndim(self.intercept_) == 0:
1199
+ self.intercept_ = float(self.intercept_)
1200
+ return self
1201
+
1202
+ def predict(self, X):
1203
+ X = pred_x(self, X)
1204
+ return (_dot(X, self.coef_.T) if _issparse(X) else X @ self.coef_.T) + self.intercept_
1205
+
1206
+
1207
+ class GramRidgeCV(Tagged, RegressorMixin, BaseEstimator):
1208
+ """scikit-learn's ``RidgeCV`` with ``cv=None``: the alpha whose
1209
+ leave-one-out mean squared error is least, every alpha from one
1210
+ eigenproblem (``examples/kernel-only/ridge-gcv.scm``). With the hat
1211
+ matrix H = Z diag(1 / (lam + alpha)) Z' (plus 1/n with an
1212
+ intercept), the leave-one-out residual is (y - yhat) / (1 - diag H),
1213
+ and diag H and yhat at every alpha are two products. Z comes from
1214
+ the eigenvectors of Xc'Xc (``gcv_mode="svd"``, the default when
1215
+ n > p, X'X by dsyrk) or of Xc Xc' (``"eigen"``, the default
1216
+ otherwise; as scikit-learn's, it takes e = c / diag G^-1 for
1217
+ c = G^-1 y, G = Xc Xc' + 11' + alpha I with the intercept's
1218
+ eigenvalue unpenalised, so that a small alpha, where H tends to I,
1219
+ loses no digits to 1 - diag H); the eigenproblem is LAPACK's dsyevd where the BLAS
1220
+ build is here. Only ``cv=None`` and ``scoring=None`` are taken.
1221
+
1222
+ Attributes after fit: alpha_, best_score_ (minus the mean squared
1223
+ leave-one-out error), coef_, intercept_, cv_results_ (with
1224
+ ``store_cv_results``: the squared errors, (n, n_alphas) or
1225
+ (n, n_targets, n_alphas)), n_features_in_.
1226
+ """
1227
+ _multi_output = True
1228
+
1229
+ def __init__(self, alphas=(0.1, 1.0, 10.0), *, fit_intercept=True, scoring=None,
1230
+ cv=None, gcv_mode=None, store_cv_results=False, alpha_per_target=False):
1231
+ self.alphas, self.fit_intercept, self.scoring, self.cv = alphas, fit_intercept, scoring, cv
1232
+ self.gcv_mode, self.store_cv_results = gcv_mode, store_cv_results
1233
+ self.alpha_per_target = alpha_per_target
1234
+
1235
+ def fit(self, X, y):
1236
+ if self.cv is not None or self.scoring is not None:
1237
+ raise ValueError("GramRidgeCV takes cv=None and scoring=None only "
1238
+ "(leave-one-out by GCV, mean squared error)")
1239
+ if self.gcv_mode not in (None, "auto", "svd", "eigen"):
1240
+ raise ValueError(f"gcv_mode={self.gcv_mode!r}: expected None, 'auto', 'svd' or 'eigen'")
1241
+ alphas = np.ascontiguousarray(np.atleast_1d(np.asarray(self.alphas, dtype=np.float64)))
1242
+ if alphas.ndim != 1 or alphas.size == 0 or not np.all(alphas > 0.0):
1243
+ raise ValueError(f"alphas={self.alphas!r}: expected positive values")
1244
+ X, y = fit_xy(self, X, y, multi_output=True)
1245
+ n, p = X.shape
1246
+ Y = y.reshape(n, -1)
1247
+ t = Y.shape[1]
1248
+ k = _gramops_kernels()
1249
+ if self.fit_intercept:
1250
+ xm, ym = X.mean(axis=0), Y.mean(axis=0)
1251
+ else:
1252
+ xm, ym = np.zeros(p), np.zeros(t)
1253
+ yc = np.ascontiguousarray(Y - ym)
1254
+ mode = self.gcv_mode if self.gcv_mode in ("svd", "eigen") else ("svd" if n > p else "eigen")
1255
+ if mode == "svd":
1256
+ G = _gram(X)
1257
+ Xs, xs = X, xm
1258
+ nm2 = n * xm * xm
1259
+ if self.fit_intercept and not np.all(np.diagonal(G) - nm2 > 1e-4 * nm2):
1260
+ # a column whose mean dwarfs its spread: the correction
1261
+ # X'X - n xm xm' would cancel its digits (_centered_gram)
1262
+ Xs, xs = np.ascontiguousarray(X - xm), np.zeros(p)
1263
+ G = _gram(Xs)
1264
+ else:
1265
+ G -= np.outer(xm, n * xm)
1266
+ m = p
1267
+ V, lam, Z, R = np.zeros((p, p)), np.zeros(p), np.zeros((n, p)), np.zeros((p, t))
1268
+ k.ridge_gcv_primal(Xs, xs, yc, np.ascontiguousarray(G), V, lam, Z, R, n, p, t)
1269
+ else:
1270
+ Xc = np.ascontiguousarray(X - xm)
1271
+ K = _gram(np.ascontiguousarray(Xc.T))
1272
+ if self.fit_intercept:
1273
+ K += 1.0
1274
+ V, lam, R = np.zeros((n, n)), np.zeros(n), np.zeros((n, t))
1275
+ drop = k.ridge_gcv_dual(K, V, lam, yc, R, n, t, int(bool(self.fit_intercept)))
1276
+ na = alphas.size
1277
+ mse = np.zeros((na, t))
1278
+ loo = np.zeros((n, t, na)) if self.store_cv_results else np.zeros(1)
1279
+ store = int(bool(self.store_cv_results))
1280
+ if mode == "svd":
1281
+ k.ridge_gcv_scan(Z, lam, R, yc, alphas, 1.0 / n if self.fit_intercept else 0.0,
1282
+ mse, loo, store, n, m, t, na)
1283
+ else:
1284
+ k.ridge_gcv_scan_dual(V, lam, R, alphas, drop, mse, loo, store, n, t, na)
1285
+ if self.alpha_per_target and t > 1:
1286
+ best = np.argmin(mse, axis=0)
1287
+ al = alphas[best]
1288
+ self.alpha_ = al
1289
+ self.best_score_ = -mse[best, np.arange(t)]
1290
+ else:
1291
+ best = int(np.argmin(mse.mean(axis=1)))
1292
+ al = np.full(t, alphas[best])
1293
+ self.alpha_ = float(alphas[best])
1294
+ self.best_score_ = float(-mse[best].mean())
1295
+ if mode == "svd":
1296
+ coef = V @ (R / (lam[:, None] + al[None, :]))
1297
+ else:
1298
+ # (Xc Xc' + alpha I)^-1 yc by the eigenvectors, then Xc' of
1299
+ # it; yc has no part along 1, so the 11' added changes nothing
1300
+ w = 1.0 / (lam[:, None] + al[None, :])
1301
+ if drop >= 0:
1302
+ w[drop] = 0.0
1303
+ coef = Xc.T @ (V @ (R * w))
1304
+ if y.ndim == 1:
1305
+ self.coef_ = coef[:, 0]
1306
+ self.intercept_ = float(ym[0] - xm @ coef[:, 0])
1307
+ if self.alpha_per_target:
1308
+ self.alpha_ = float(np.ravel(self.alpha_)[0])
1309
+ self.best_score_ = float(np.ravel(self.best_score_)[0])
1310
+ else:
1311
+ self.coef_ = coef.T
1312
+ self.intercept_ = ym - xm @ coef
1313
+ if self.store_cv_results:
1314
+ self.cv_results_ = loo[:, 0, :] if y.ndim == 1 else loo
1315
+ return self
1316
+
1317
+ def predict(self, X):
1318
+ return pred_x(self, X) @ self.coef_.T + self.intercept_
1319
+
1320
+
1321
+ class CovBayesianRidge(Tagged, RegressorMixin, BaseEstimator):
1322
+ """Bayesian ridge regression, scikit-learn's ``BayesianRidge``,
1323
+ with the linear algebra in the eigenbasis of the Gram matrix.
1324
+
1325
+ The model, the defaults (``max_iter=300``, ``tol=1e-3``, the four
1326
+ gamma hyperpriors at 1e-6, ``alpha`` starting at ``1/var(y)``,
1327
+ ``lambda`` at 1) and the iteration are scikit-learn's: MacKay's
1328
+ updates of the noise precision ``alpha`` and the weight precision
1329
+ ``lambda``, the posterior mean recomputed after each, a stop when
1330
+ the mean moves by less than ``tol`` in L1. What differs is where
1331
+ the work goes. scikit-learn takes the SVD of X once and then, per
1332
+ iteration, multiplies by X again for the squared error, O(n p).
1333
+ Here, for n > p, X enters once, through X'X and X'y: one symmetric
1334
+ eigendecomposition, after which the posterior mean, its squared
1335
+ norm and the squared error are sums over the p eigenvalues, O(p) per
1336
+ iteration. For n <= p the same is done with the n x n kernel
1337
+ matrix X X'. With ``fit_intercept`` the data are centred, as in
1338
+ scikit-learn, and the Gram is centred in place.
1339
+
1340
+ Attributes after fit: coef_, intercept_, alpha_, lambda_, sigma_
1341
+ (the posterior covariance of the weights, p x p), n_iter_.
1342
+ """
1343
+
1344
+ def __init__(self, *, max_iter=300, tol=1e-3, alpha_1=1e-6,
1345
+ alpha_2=1e-6, lambda_1=1e-6, lambda_2=1e-6,
1346
+ alpha_init=None, lambda_init=None, fit_intercept=True):
1347
+ self.max_iter, self.tol = max_iter, tol
1348
+ self.alpha_1, self.alpha_2 = alpha_1, alpha_2
1349
+ self.lambda_1, self.lambda_2 = lambda_1, lambda_2
1350
+ self.alpha_init, self.lambda_init = alpha_init, lambda_init
1351
+ self.fit_intercept = fit_intercept
1352
+
1353
+ def fit(self, X, y):
1354
+ X, y = fit_xy(self, X, y)
1355
+ n, p = X.shape
1356
+ max_iter, tol = int(self.max_iter), float(self.tol)
1357
+ a1, a2 = float(self.alpha_1), float(self.alpha_2)
1358
+ l1, l2 = float(self.lambda_1), float(self.lambda_2)
1359
+ y_var = float(y.var())
1360
+ if self.fit_intercept:
1361
+ xm, ym = X.mean(axis=0), float(y.mean())
1362
+ else:
1363
+ xm, ym = np.zeros(p), 0.0
1364
+ tall = n > p
1365
+ if tall:
1366
+ # X'X and X'y of the centred data, without centring X
1367
+ G = X.T @ X
1368
+ c = X.T @ y
1369
+ if self.fit_intercept:
1370
+ G -= n * np.outer(xm, xm)
1371
+ c -= n * ym * xm
1372
+ e, V = np.linalg.eigh(G)
1373
+ z = V.T @ c
1374
+ yy = float(y @ y) - n * ym * ym
1375
+ else:
1376
+ Xc = X - xm if self.fit_intercept else X
1377
+ yc = y - ym
1378
+ e, U = np.linalg.eigh(Xc @ Xc.T)
1379
+ u = U.T @ yc
1380
+ e = np.maximum(e, 0.0)
1381
+
1382
+ def mean_stats(alpha, lam):
1383
+ # the posterior mean at (alpha, lam), its squared norm, and
1384
+ # the squared error, without touching X when n > p
1385
+ r = lam / alpha
1386
+ if tall:
1387
+ w = z / (e + r)
1388
+ coef = V @ w
1389
+ sse = yy - 2.0 * float(w @ z) + float((e * w) @ w)
1390
+ return coef, float(w @ w), max(sse, 0.0)
1391
+ d = u / (e + r)
1392
+ coef = Xc.T @ (U @ d)
1393
+ resid = yc - Xc @ coef
1394
+ return coef, float((e * d) @ d), float(resid @ resid)
1395
+
1396
+ eps = np.finfo(np.float64).eps
1397
+ alpha = 1.0 / (y_var + eps) if self.alpha_init is None else float(self.alpha_init)
1398
+ lam = 1.0 if self.lambda_init is None else float(self.lambda_init)
1399
+ old = None
1400
+ for it in range(max_iter):
1401
+ coef, cc, sse = mean_stats(alpha, lam)
1402
+ gamma = float(np.sum(alpha * e / (lam + alpha * e)))
1403
+ lam = (gamma + 2 * l1) / (cc + 2 * l2)
1404
+ alpha = (n - gamma + 2 * a1) / (sse + 2 * a2)
1405
+ if it != 0 and float(np.sum(np.abs(old - coef))) < tol:
1406
+ break
1407
+ old = coef
1408
+ self.n_iter_ = it + 1
1409
+ self.alpha_, self.lambda_ = alpha, lam
1410
+ self.coef_, _, _ = mean_stats(alpha, lam)
1411
+ self.intercept_ = ym - float(xm @ self.coef_) if self.fit_intercept else 0.0
1412
+ self.X_offset_ = xm
1413
+ # the posterior covariance (lambda I + alpha X'X)^-1
1414
+ if tall:
1415
+ self.sigma_ = (V / (alpha * e + lam)) @ V.T
1416
+ else:
1417
+ # Woodbury through the kernel side: (1/lam)(I - X'U D U'X),
1418
+ # D = alpha / (lam + alpha e)
1419
+ B = Xc.T @ U
1420
+ self.sigma_ = (np.eye(p) - (B * (alpha / (lam + alpha * e))) @ B.T) / lam
1421
+ return self
1422
+
1423
+ def predict(self, X, return_std=False):
1424
+ X = pred_x(self, X)
1425
+ mean = X @ self.coef_ + self.intercept_
1426
+ if not return_std:
1427
+ return mean
1428
+ Xc = X - self.X_offset_
1429
+ var = np.einsum("ij,jk,ik->i", Xc, self.sigma_, Xc) + 1.0 / self.alpha_
1430
+ return mean, np.sqrt(var)
1431
+
1432
+ def _classifier_kernels():
1433
+ # imported on first use: the classifiers are their own library
1434
+ from ._generated import _loader_classifiers
1435
+ return _loader_classifiers
1436
+
1437
+
1438
+ def _binary_labels(y):
1439
+ """Two classes as (classes_, y in {-1, +1}), classes_[1] the +1."""
1440
+ y = np.asarray(y)
1441
+ classes = np.unique(y)
1442
+ if classes.size == 1:
1443
+ raise ValueError("expected two classes, got 1 class")
1444
+ if classes.size != 2:
1445
+ raise ValueError("Only binary classification is supported. The type of the target "
1446
+ f"is multiclass ({classes.size} classes).")
1447
+ return classes, np.where(y == classes[1], 1.0, -1.0)
1448
+
1449
+
1450
+ def _seed(random_state):
1451
+ # the solvers' Park-Miller generator wants a seed in [1, 2^31 - 2]
1452
+ return int(random_state) % 2147483646 + 1
1453
+
1454
+
1455
+ class LinearSVM(Tagged, ClassifierMixin, BaseEstimator):
1456
+ """The L1-loss (hinge) linear SVM by liblinear's own algorithm.
1457
+
1458
+ ``examples/kernel-only/svm-liblinear.scm`` translated plainly:
1459
+ liblinear's solve_l2r_l1l2_svc, dual coordinate descent with a
1460
+ random order in every sweep, shrinking, and the projected-gradient
1461
+ stop -- what scikit-learn's ``LinearSVC(loss="hinge", dual=True,
1462
+ fit_intercept=False)`` runs, on the same problem
1463
+
1464
+ min_w 1/2 ||w||^2 + C sum_i max(0, 1 - y_i w.x_i).
1465
+
1466
+ No intercept (as ``fit_intercept=False``); two classes, the second
1467
+ of ``classes_`` being the positive one. ``tol`` and ``max_iter``
1468
+ are LinearSVC's (the projected-gradient span and the sweep cap).
1469
+
1470
+ Attributes after fit: classes_, coef_, dual_coef_ (the alphas),
1471
+ n_iter_.
1472
+ """
1473
+
1474
+ _binary_only = True
1475
+
1476
+ def __init__(self, C=1.0, tol=1e-4, max_iter=1000, random_state=0):
1477
+ self.C, self.tol, self.max_iter = C, tol, max_iter
1478
+ self.random_state = random_state
1479
+
1480
+ def fit(self, X, y):
1481
+ X, y = fit_xy(self, X, y, classifier=True)
1482
+ n, p = X.shape
1483
+ self.classes_, ys = _binary_labels(y)
1484
+ w = np.zeros(p)
1485
+ alpha = np.zeros(n)
1486
+ xnorm = np.zeros(n)
1487
+ self.n_iter_ = _classifier_kernels().svm_liblinear(
1488
+ X, ys, w, alpha, xnorm, float(self.C), int(self.max_iter), float(self.tol),
1489
+ _seed(self.random_state), n, p)
1490
+ self.coef_, self.dual_coef_ = w, alpha
1491
+ return self
1492
+
1493
+ def decision_function(self, X):
1494
+ return pred_x(self, X) @ self.coef_
1495
+
1496
+ def predict(self, X):
1497
+ z = self.decision_function(X)
1498
+ return self.classes_[(z > 0).astype(int)]
1499
+
1500
+
1501
+ class _KernelMatrix:
1502
+ # the kernel matrix of KernelSVM and KernelSVR, as SVC and SVR take
1503
+ # it: rbf (gamma "scale", "auto" or a number), linear, or precomputed
1504
+ def _k(self, A, B):
1505
+ if self.kernel == "linear":
1506
+ return A @ B.T
1507
+ if self.kernel == "rbf":
1508
+ if A.shape[0] * B.shape[0] < 200_000:
1509
+ # numpy's vectorised exp, while the matrix sits in cache:
1510
+ # 0.14 ms to the loop's 0.31 at 200 x 200
1511
+ sa = (A * A).sum(1)[:, None]
1512
+ sb = (B * B).sum(1)[None, :]
1513
+ return np.exp(-self._gamma * np.maximum(sa + sb - 2.0 * (A @ B.T), 0.0))
1514
+ # the product by BLAS, the rest in place by svm-smo.scm's
1515
+ # rbf-from-products (on every thread of an OpenMP build;
1516
+ # 76 ms to numpy's 96 at 3,000 on one core, 50 to 105 on 20)
1517
+ G = np.ascontiguousarray(A @ B.T)
1518
+ _classifier_kernels().rbf_from_products(
1519
+ G, (A * A).sum(1), (B * B).sum(1), float(self._gamma), A.shape[0], B.shape[0])
1520
+ return G
1521
+ raise ValueError(f"kernel {self.kernel!r}: expected rbf, linear or precomputed")
1522
+
1523
+ def _train_kernel(self, X):
1524
+ if self.kernel == "precomputed":
1525
+ return X
1526
+ p = X.shape[1]
1527
+ if self.gamma == "scale":
1528
+ v = float(X.var())
1529
+ self._gamma = 1.0 / (p * v) if v > 0 else 1.0
1530
+ elif self.gamma == "auto":
1531
+ self._gamma = 1.0 / p
1532
+ else:
1533
+ self._gamma = float(self.gamma)
1534
+ return self._k(X, X)
1535
+
1536
+ def _support_kernel(self, X):
1537
+ X = pred_x(self, X)
1538
+ if self.kernel == "precomputed":
1539
+ return X[:, self.support_]
1540
+ return self._k(X, self.support_vectors_)
1541
+
1542
+
1543
+ class KernelSVM(Tagged, ClassifierMixin, _KernelMatrix, BaseEstimator):
1544
+ """C-SVC by libsvm's own algorithm, over the whole kernel matrix.
1545
+
1546
+ ``examples/kernel-only/svm-smo.scm`` translated plainly: libsvm's
1547
+ Solver::Solve -- SMO with the second-order working-set selection
1548
+ (WSS3), shrinking with gradient reconstruction, and the bias -- the
1549
+ solver scikit-learn's ``SVC`` runs, on the same problem (with the
1550
+ intercept). The kernel matrix is built once in numpy and held
1551
+ whole, n x n doubles (800 MB at n = 10,000): libsvm with every row
1552
+ in its cache. ``kernel`` is "rbf" (``gamma`` "scale", "auto" or a
1553
+ number, as in SVC), "linear", or "precomputed" (X is then the
1554
+ kernel matrix, and decision_function takes the kernel between new
1555
+ points and the training points).
1556
+
1557
+ Attributes after fit: classes_, support_, dual_coef_ (alpha_i y_i
1558
+ over the support), intercept_, n_iter_; support_vectors_ unless
1559
+ precomputed.
1560
+ """
1561
+
1562
+ _binary_only = True
1563
+ _pairwise = True
1564
+
1565
+ def __init__(self, C=1.0, kernel="rbf", gamma="scale", tol=1e-3, max_iter=-1):
1566
+ self.C, self.kernel, self.gamma = C, kernel, gamma
1567
+ self.tol, self.max_iter = tol, max_iter
1568
+
1569
+ def fit(self, X, y):
1570
+ X, y = fit_xy(self, X, y, classifier=True)
1571
+ self.classes_, ys = _binary_labels(y)
1572
+ n = ys.size
1573
+ K = self._train_kernel(X)
1574
+ alpha = np.zeros(n)
1575
+ rho = np.zeros(1)
1576
+ iters = int(self.max_iter) if self.max_iter > 0 else 10_000_000
1577
+ self.n_iter_ = _classifier_kernels().svm_smo(
1578
+ np.ascontiguousarray(K), ys, alpha, rho, float(self.C), iters, float(self.tol), n)
1579
+ self.support_ = np.flatnonzero(alpha > 0)
1580
+ self.dual_coef_ = (alpha * ys)[self.support_]
1581
+ self.intercept_ = -float(rho[0])
1582
+ if self.kernel != "precomputed":
1583
+ self.support_vectors_ = X[self.support_]
1584
+ return self
1585
+
1586
+ def decision_function(self, X):
1587
+ return self._support_kernel(X) @ self.dual_coef_ + self.intercept_
1588
+
1589
+ def predict(self, X):
1590
+ z = self.decision_function(X)
1591
+ return self.classes_[(z > 0).astype(int)]
1592
+
1593
+
1594
+ class LinearSVR(Tagged, RegressorMixin, BaseEstimator):
1595
+ """The linear epsilon-SVR with the L1 loss, by liblinear's own algorithm.
1596
+
1597
+ ``examples/kernel-only/svr-liblinear.scm`` translated plainly:
1598
+ liblinear's solve_l2r_l1l2_svr (dual coordinate descent, random
1599
+ order, shrinking) -- what scikit-learn's
1600
+ ``LinearSVR(loss="epsilon_insensitive", dual=True,
1601
+ fit_intercept=False)`` runs, on the same problem
1602
+
1603
+ min_w 1/2 ||w||^2 + C sum_i max(0, |y_i - w.x_i| - epsilon).
1604
+
1605
+ ``epsilon`` defaults to 0, ``tol`` to 1e-4 and ``max_iter`` to 1000
1606
+ sweeps, as in LinearSVR; no intercept.
1607
+
1608
+ Attributes after fit: coef_, dual_coef_ (the betas), n_iter_.
1609
+ """
1610
+
1611
+ def __init__(self, C=1.0, epsilon=0.0, tol=1e-4, max_iter=1000, random_state=0):
1612
+ self.C, self.epsilon = C, epsilon
1613
+ self.tol, self.max_iter = tol, max_iter
1614
+ self.random_state = random_state
1615
+
1616
+ def fit(self, X, y):
1617
+ X, y = fit_xy(self, X, y)
1618
+ n, p = X.shape
1619
+ w = np.zeros(p)
1620
+ beta = np.zeros(n)
1621
+ xnorm = np.zeros(n)
1622
+ self.n_iter_ = _classifier_kernels().svr_liblinear(
1623
+ X, y, w, beta, xnorm, float(self.C), float(self.epsilon), int(self.max_iter),
1624
+ float(self.tol), _seed(self.random_state), n, p)
1625
+ self.coef_, self.dual_coef_ = w, beta
1626
+ self.intercept_ = 0.0
1627
+ return self
1628
+
1629
+ def predict(self, X):
1630
+ return pred_x(self, X) @ self.coef_
1631
+
1632
+
1633
+ class KernelSVR(Tagged, RegressorMixin, _KernelMatrix, BaseEstimator):
1634
+ """epsilon-SVR by libsvm's own algorithm, over the whole kernel matrix.
1635
+
1636
+ The same translated SMO solver as KernelSVM (``svm-smo.scm``), set
1637
+ up as libsvm's solve_epsilon_svr sets it up: the 2n variables
1638
+ alpha and alpha* with linear terms epsilon -/+ y_i. scikit-learn's
1639
+ ``SVR``, with the intercept; ``epsilon=0.1``, ``tol=1e-3`` and the
1640
+ kernels as there. The kernel matrix is held whole.
1641
+
1642
+ Attributes after fit: support_, dual_coef_ (alpha - alpha* over the
1643
+ support), intercept_, n_iter_; support_vectors_ unless precomputed.
1644
+ """
1645
+
1646
+ _pairwise = True
1647
+
1648
+ def __init__(self, C=1.0, epsilon=0.1, kernel="rbf", gamma="scale", tol=1e-3, max_iter=-1):
1649
+ self.C, self.epsilon, self.kernel, self.gamma = C, epsilon, kernel, gamma
1650
+ self.tol, self.max_iter = tol, max_iter
1651
+
1652
+ def fit(self, X, y):
1653
+ X, y = fit_xy(self, X, y)
1654
+ n = y.size
1655
+ K = self._train_kernel(X)
1656
+ beta = np.zeros(n)
1657
+ rho = np.zeros(1)
1658
+ iters = int(self.max_iter) if self.max_iter > 0 else 10_000_000
1659
+ self.n_iter_ = _classifier_kernels().svr_smo(
1660
+ np.ascontiguousarray(K), y, beta, rho, float(self.C), float(self.epsilon), iters,
1661
+ float(self.tol), n)
1662
+ self.support_ = np.flatnonzero(beta != 0)
1663
+ self.dual_coef_ = beta[self.support_]
1664
+ self.intercept_ = -float(rho[0])
1665
+ if self.kernel != "precomputed":
1666
+ self.support_vectors_ = X[self.support_]
1667
+ return self
1668
+
1669
+ def predict(self, X):
1670
+ return self._support_kernel(X) @ self.dual_coef_ + self.intercept_
1671
+
1672
+
1673
+ def nmf_backend():
1674
+ """The variant CDNMF takes by default: cublas when a device
1675
+ answers, else blas, else loops."""
1676
+ built = nmf_backends()
1677
+ if not built:
1678
+ raise ImportError("scm2cpp_learn: no variant of the derived NMF was built")
1679
+ if "cublas" in built and cuda_available():
1680
+ return "cublas"
1681
+ cpu = [v for v in built if v != "cublas"]
1682
+ return cpu[0] if cpu else built[0]
1683
+
1684
+
1685
+ class CDNMF(Tagged, TransformerMixin, BaseEstimator):
1686
+ """Non-negative matrix factorization by coordinate descent, the
1687
+ translator's derivation end to end.
1688
+
1689
+ ``examples/kernel-only/nmf-cd.scm`` writes scikit-learn's
1690
+ NMF(solver="cd") iteration the plain way, with the residual
1691
+ R = X - W H: each half step sweeps the coordinates of one factor and
1692
+ moves R along the other. ``--derive`` turns that half step into
1693
+ scikit-learn's own form -- the memo X H' - W H H' over the hoisted
1694
+ Gram H H', with R never formed -- and ``--blas`` / ``--cublas`` hand
1695
+ the products to (cu)BLAS. Nothing of the Gram form is written by
1696
+ hand. The iteration, the stopping rule (the projected-gradient
1697
+ violation down to ``tol`` times the first iteration's) and the
1698
+ result are scikit-learn's with Frobenius loss, no regularization and
1699
+ no shuffling.
1700
+
1701
+ ``init`` is "random" (scikit-learn's: |N(0, 1)| scaled by
1702
+ sqrt(mean(X) / k), H drawn before W, from ``random_state``) or
1703
+ "custom" (W and H given to fit_transform). scikit-learn's default
1704
+ "nndsvda" is not offered; pass "custom" with its W and H for an
1705
+ exact comparison. ``backend`` is "cublas", "blas" or "loops", or
1706
+ None for the best built (``nmf_backend()``).
1707
+
1708
+ ``transform`` solves for W with H fixed by the same coordinate
1709
+ descent (scikit-learn's NMF.transform), in numpy.
1710
+
1711
+ Attributes after fit: components_ (H, k x p), n_components_, n_iter_,
1712
+ reconstruction_err_ (||X - W H||_F).
1713
+ """
1714
+ _positive_X = True
1715
+
1716
+ def __init__(self, n_components=None, *, init="random", tol=1e-4, max_iter=200,
1717
+ random_state=None, backend=None):
1718
+ self.n_components = n_components
1719
+ self.init, self.tol, self.max_iter = init, tol, max_iter
1720
+ self.random_state = random_state
1721
+ self.backend = backend
1722
+
1723
+ def _lib(self):
1724
+ import importlib
1725
+ v = self.backend or nmf_backend()
1726
+ return importlib.import_module(f"{__name__}._generated._loader_nmf_{v}")
1727
+
1728
+ def fit_transform(self, X, y=None, W=None, H=None):
1729
+ X = fit_x(self, X)
1730
+ if X.min() < 0:
1731
+ raise ValueError("Negative values in data passed to CDNMF (input X)")
1732
+ n, p = X.shape
1733
+ k = p if self.n_components is None else int(self.n_components)
1734
+ if k < 1:
1735
+ raise ValueError(f"n_components must be at least 1, got {self.n_components!r}")
1736
+ if self.init == "custom":
1737
+ if W is None or H is None:
1738
+ raise ValueError('init="custom" needs W and H')
1739
+ W = np.array(W, dtype=np.float64, copy=True)
1740
+ H = np.array(H, dtype=np.float64)
1741
+ elif self.init == "random":
1742
+ rng = np.random.RandomState(self.random_state)
1743
+ avg = np.sqrt(X.mean() / k)
1744
+ H = np.abs(avg * rng.standard_normal(size=(k, p)))
1745
+ W = np.abs(avg * rng.standard_normal(size=(n, k)))
1746
+ else:
1747
+ raise ValueError(f"init {self.init!r}: expected 'random' or 'custom'")
1748
+ W = np.ascontiguousarray(W)
1749
+ HT = np.ascontiguousarray(H.T)
1750
+ XT = np.ascontiguousarray(X.T)
1751
+ self.n_iter_ = self._lib().nmf(X, XT, W, HT, int(self.max_iter), float(self.tol),
1752
+ n, p, k)
1753
+ self.components_ = np.ascontiguousarray(HT.T)
1754
+ self.n_components_ = k
1755
+ self.reconstruction_err_ = float(np.linalg.norm(X - W @ self.components_))
1756
+ return W
1757
+
1758
+ def fit(self, X, y=None, W=None, H=None):
1759
+ self.fit_transform(X, W=W, H=H)
1760
+ return self
1761
+
1762
+ def transform(self, X):
1763
+ X = pred_x(self, X)
1764
+ if X.min() < 0:
1765
+ raise ValueError("Negative values in data passed to CDNMF (input X)")
1766
+ H = self.components_
1767
+ k = H.shape[0]
1768
+ HHt = H @ H.T
1769
+ XHt = X @ H.T
1770
+ avg = np.sqrt(X.mean() / k) if X.size else 0.0
1771
+ W = np.full((X.shape[0], k), avg)
1772
+ tol = float(self.tol)
1773
+ # the half step of the fit on W alone, H fixed; the stop on the
1774
+ # projected gradient, measured against the first sweep's, as there
1775
+ first = None
1776
+ for _ in range(int(self.max_iter)):
1777
+ viol = 0.0
1778
+ for j in range(k):
1779
+ if HHt[j, j] <= 0.0:
1780
+ continue
1781
+ grad = W @ HHt[:, j] - XHt[:, j]
1782
+ pg = np.where(W[:, j] == 0.0, np.minimum(grad, 0.0), grad)
1783
+ viol += float(np.abs(pg).sum())
1784
+ W[:, j] = np.maximum(W[:, j] - grad / HHt[j, j], 0.0)
1785
+ if first is None:
1786
+ first = viol
1787
+ if first == 0.0 or viol / first <= tol:
1788
+ break
1789
+ return W
1790
+
1791
+
1792
+ class CDGraphicalLasso(Tagged, BaseEstimator):
1793
+ """The graphical lasso, scikit-learn's own algorithm translated.
1794
+
1795
+ ``examples/kernel-only/graphical-lasso.scm`` is scikit-learn's
1796
+ _graphical_lasso in mode "cd" and its inner solver
1797
+ enet_coordinate_descent_gram (the gap-safe rule included), written
1798
+ out whole; ``--blas`` makes its two matrix-vector products dgemv.
1799
+ The same model and stopping rule as ``GraphicalLasso(mode="cd")``:
1800
+ ``alpha``, ``tol``, ``enet_tol``, ``max_iter`` and
1801
+ ``assume_centered`` mean what they mean there. scikit-learn's
1802
+ ``costs_`` (the objective each iteration, a log-determinant) is not
1803
+ computed.
1804
+
1805
+ Attributes after fit: covariance_, precision_, location_, n_iter_.
1806
+ """
1807
+
1808
+ def __init__(self, alpha=0.01, *, tol=1e-4, enet_tol=1e-4, max_iter=100,
1809
+ assume_centered=False):
1810
+ self.alpha, self.tol, self.enet_tol = alpha, tol, enet_tol
1811
+ self.max_iter, self.assume_centered = max_iter, assume_centered
1812
+
1813
+ def fit(self, X, y=None):
1814
+ import importlib
1815
+ from ._libfind import gramops_backend
1816
+ X = fit_x(self, X, ensure_min_samples=2, ensure_min_features=2)
1817
+ n, p = X.shape
1818
+ self.location_ = np.zeros(p) if self.assume_centered else X.mean(axis=0)
1819
+ Xc = X - self.location_
1820
+ emp = np.ascontiguousarray(Xc.T @ Xc / n)
1821
+ lib = importlib.import_module(f"{__name__}._generated._loader_gramops_{gramops_backend()}")
1822
+ self.covariance_ = np.zeros((p, p))
1823
+ self.precision_ = np.zeros((p, p))
1824
+ self.n_iter_ = lib.graphical_lasso(emp, self.covariance_, self.precision_,
1825
+ float(self.alpha), int(self.max_iter),
1826
+ float(self.tol), float(self.enet_tol), p)
1827
+ if not np.isfinite(self.precision_).all():
1828
+ raise FloatingPointError("the system is too ill-conditioned for this solver")
1829
+ return self
1830
+
1831
+
1832
+ class LinearRANSAC(Tagged, RegressorMixin, BaseEstimator):
1833
+ """RANSAC for a linear model, scikit-learn's algorithm translated.
1834
+
1835
+ ``examples/kernel-only/ransac.scm`` is RANSACRegressor.fit around
1836
+ LinearRegression, written out whole: per trial, least squares with
1837
+ an intercept on a subset of ``min_samples`` points, the inliers
1838
+ within ``residual_threshold``, the fit kept by inlier count and then
1839
+ R^2, the trial count lowered by scikit-learn's _dynamic_max_trials;
1840
+ finally least squares on the best inliers. The defaults are
1841
+ RANSACRegressor's (min_samples p + 1, the threshold the MAD of y,
1842
+ max_trials 100, stop_probability 0.99).
1843
+
1844
+ The subsets are drawn here, ``max_trials`` of them, before the
1845
+ trials run. With scikit-learn installed they are drawn exactly as
1846
+ RANSACRegressor draws them (sample_without_replacement on a
1847
+ RandomState of ``random_state``), so the result is scikit-learn's;
1848
+ without it, numpy's choice draws different subsets.
1849
+
1850
+ Attributes after fit: coef_, intercept_, inlier_mask_, n_trials_.
1851
+ """
1852
+
1853
+ def __init__(self, *, min_samples=None, residual_threshold=None, max_trials=100,
1854
+ stop_probability=0.99, random_state=None):
1855
+ self.min_samples, self.residual_threshold = min_samples, residual_threshold
1856
+ self.max_trials, self.stop_probability = max_trials, stop_probability
1857
+ self.random_state = random_state
1858
+
1859
+ def fit(self, X, y):
1860
+ X, y = fit_xy(self, X, y)
1861
+ n, p = X.shape
1862
+ max_trials = int(self.max_trials)
1863
+ ms = p + 1 if self.min_samples is None else int(self.min_samples)
1864
+ thr = (float(np.median(np.abs(y - np.median(y)))) if self.residual_threshold is None
1865
+ else float(self.residual_threshold))
1866
+ rs = np.random.RandomState(self.random_state)
1867
+ try:
1868
+ from sklearn.utils.random import sample_without_replacement
1869
+ draw = lambda: sample_without_replacement(n, ms, random_state=rs)
1870
+ except ImportError:
1871
+ draw = lambda: rs.choice(n, ms, replace=False)
1872
+ if ms > n:
1873
+ raise ValueError(f"min_samples may not be larger than the number of samples: "
1874
+ f"n_samples = {n}")
1875
+ subsets = np.array([draw() for _ in range(max_trials)], dtype=np.float64)
1876
+ coef = np.zeros(p)
1877
+ mask = np.zeros(n)
1878
+ out = np.zeros(1)
1879
+ self.n_trials_ = _classifier_kernels().ransac(
1880
+ X, y, subsets, coef, mask, out, max_trials, ms, thr, float(self.stop_probability),
1881
+ n, p)
1882
+ self.coef_, self.intercept_ = coef, float(out[0])
1883
+ self.inlier_mask_ = mask.astype(bool)
1884
+ return self
1885
+
1886
+ def predict(self, X):
1887
+ return pred_x(self, X) @ self.coef_ + self.intercept_
1888
+
1889
+
1890
+ def _center(X, y, fit_intercept):
1891
+ X = np.ascontiguousarray(X, dtype=np.float64)
1892
+ y = np.ascontiguousarray(y, dtype=np.float64)
1893
+ if fit_intercept:
1894
+ xm, ym = X.mean(axis=0), float(y.mean())
1895
+ return np.ascontiguousarray(X - xm), y - ym, xm, ym
1896
+ return X, y, np.zeros(X.shape[1]), 0.0
1897
+
1898
+
1899
+ _SGD_LOSS = {"hinge": 0, "squared_error": 1, "perceptron": 2, "epsilon_insensitive": 3}
1900
+ _SGD_LR = {"optimal": 0, "invscaling": 1, "constant": 2, "pa1": 3, "pa2": 4}
1901
+
1902
+
1903
+ class _SGDLinear(BaseEstimator):
1904
+ # the shared run; the subclasses' __init__ name the parameters
1905
+ # (scikit-learn reads them off the signature), so this one has none
1906
+ def _set(self, *, loss, penalty, alpha, max_iter, tol, n_iter_no_change, fit_intercept,
1907
+ learning_rate, eta0, power_t, epsilon=0.1):
1908
+ self.loss, self.penalty, self.alpha = loss, penalty, alpha
1909
+ self.max_iter, self.tol = max_iter, tol
1910
+ self.n_iter_no_change, self.fit_intercept = n_iter_no_change, fit_intercept
1911
+ self.learning_rate, self.eta0, self.power_t = learning_rate, eta0, power_t
1912
+ self.epsilon = epsilon
1913
+
1914
+ def _run(self, X, y):
1915
+ loss = getattr(self, "loss", "perceptron")
1916
+ lr = getattr(self, "learning_rate", "constant")
1917
+ penalty = getattr(self, "penalty", None)
1918
+ if loss not in _SGD_LOSS or lr not in _SGD_LR:
1919
+ raise ValueError("loss is one of %s, learning_rate one of %s"
1920
+ % (sorted(_SGD_LOSS), sorted(_SGD_LR)))
1921
+ if penalty not in ("l2", None):
1922
+ raise ValueError("penalty is 'l2' or None")
1923
+ n, p = X.shape
1924
+ w = np.zeros(p)
1925
+ out = np.zeros(1)
1926
+ self.n_iter_ = _classifier_kernels().sgd(
1927
+ X, np.ascontiguousarray(y, dtype=np.float64), w, out,
1928
+ _SGD_LOSS[loss], _SGD_LR[lr],
1929
+ 1 if penalty == "l2" else 0, float(getattr(self, "alpha", 1e-4)),
1930
+ float(self.eta0), float(getattr(self, "power_t", 0.5)),
1931
+ float(getattr(self, "epsilon", 0.1)), int(self.max_iter), float(self.tol),
1932
+ int(self.n_iter_no_change), 1 if self.fit_intercept else 0, n, p)
1933
+ self.coef_, self.intercept_ = w, float(out[0])
1934
+ return self
1935
+
1936
+ def _linear(self, X):
1937
+ return pred_x(self, X) @ self.coef_ + self.intercept_
1938
+
1939
+
1940
+ class SGDLinearClassifier(Tagged, ClassifierMixin, _SGDLinear):
1941
+ """scikit-learn's SGDClassifier by its own _plain_sgd translated
1942
+ (``examples/kernel-only/sgd.scm``), with shuffle=False: the points
1943
+ are visited in order. scikit-learn's shuffling draws from its own
1944
+ xorshift generator, which the kernel does not reproduce, so compare
1945
+ against ``SGDClassifier(shuffle=False)``, which this matches to
1946
+ rounding. loss "hinge" or "perceptron", penalty "l2" or None,
1947
+ learning_rate "optimal", "constant", "invscaling", "pa1" or "pa2"
1948
+ (the passive-aggressive steps, eta0 their C: scikit-learn's
1949
+ replacement for PassiveAggressiveClassifier). Two classes, the
1950
+ second of ``classes_`` positive.
1951
+
1952
+ Attributes after fit: classes_, coef_, intercept_, n_iter_.
1953
+ """
1954
+
1955
+ def __init__(self, *, loss="hinge", penalty="l2", alpha=1e-4, max_iter=1000, tol=1e-3,
1956
+ n_iter_no_change=5, fit_intercept=True, learning_rate="optimal",
1957
+ eta0=0.01, power_t=0.5):
1958
+ self._set(loss=loss, penalty=penalty, alpha=alpha, max_iter=max_iter,
1959
+ tol=tol, n_iter_no_change=n_iter_no_change,
1960
+ fit_intercept=fit_intercept, learning_rate=learning_rate,
1961
+ eta0=eta0, power_t=power_t)
1962
+ del self.epsilon
1963
+
1964
+ _binary_only = True
1965
+
1966
+ def fit(self, X, y):
1967
+ X, y = fit_xy(self, X, y, classifier=True)
1968
+ self.classes_, ys = _binary_labels(y)
1969
+ return self._run(X, ys)
1970
+
1971
+ def decision_function(self, X):
1972
+ return self._linear(X)
1973
+
1974
+ def predict(self, X):
1975
+ z = self.decision_function(X)
1976
+ return self.classes_[(z > 0).astype(int)]
1977
+
1978
+
1979
+ class SGDLinearRegressor(Tagged, RegressorMixin, _SGDLinear):
1980
+ """scikit-learn's SGDRegressor by its own _plain_sgd translated, with
1981
+ shuffle=False (see SGDLinearClassifier). loss "squared_error" or
1982
+ "epsilon_insensitive" (``epsilon``), penalty "l2" or None,
1983
+ learning_rate "invscaling" (the default), "constant", "optimal",
1984
+ "pa1" or "pa2" (scikit-learn's replacement for
1985
+ PassiveAggressiveRegressor).
1986
+
1987
+ Attributes after fit: coef_, intercept_, n_iter_.
1988
+ """
1989
+
1990
+ def __init__(self, *, loss="squared_error", penalty="l2", alpha=1e-4, max_iter=1000,
1991
+ tol=1e-3, n_iter_no_change=5, fit_intercept=True,
1992
+ learning_rate="invscaling", eta0=0.01, power_t=0.25, epsilon=0.1):
1993
+ self._set(loss=loss, penalty=penalty, alpha=alpha, max_iter=max_iter,
1994
+ tol=tol, n_iter_no_change=n_iter_no_change,
1995
+ fit_intercept=fit_intercept, learning_rate=learning_rate,
1996
+ eta0=eta0, power_t=power_t, epsilon=epsilon)
1997
+
1998
+ def fit(self, X, y):
1999
+ X, y = fit_xy(self, X, y)
2000
+ return self._run(X, y)
2001
+
2002
+ def predict(self, X):
2003
+ return self._linear(X)
2004
+
2005
+
2006
+ class SGDPerceptron(SGDLinearClassifier):
2007
+ """scikit-learn's Perceptron: SGDClassifier with the perceptron's
2008
+ hinge (threshold 0), no penalty and the constant step eta0 = 1, by
2009
+ the same translated _plain_sgd, shuffle=False.
2010
+
2011
+ Attributes after fit: classes_, coef_, intercept_, n_iter_.
2012
+ """
2013
+
2014
+ # the loss, penalty and step rule are fixed, not parameters: _run
2015
+ # falls back to the perceptron's when the attributes are absent
2016
+ def __init__(self, *, max_iter=1000, tol=1e-3, n_iter_no_change=5, fit_intercept=True,
2017
+ eta0=1.0):
2018
+ self.max_iter, self.tol, self.n_iter_no_change = max_iter, tol, n_iter_no_change
2019
+ self.fit_intercept, self.eta0 = fit_intercept, eta0
2020
+
2021
+
2022
+ class GramOMP(Tagged, RegressorMixin, BaseEstimator):
2023
+ """Orthogonal matching pursuit over the Gram matrix, scikit-learn's
2024
+ own algorithm translated (``examples/kernel-only/omp.scm``:
2025
+ orthogonal_mp_gram and _gram_omp, X'X and X'y by dsyrk and dgemv).
2026
+ ``OrthogonalMatchingPursuit`` takes this route for n > p
2027
+ (precompute="auto"); here it is taken always. ``n_nonzero_coefs``
2028
+ defaults, as there, to 10% of the features.
2029
+
2030
+ Attributes after fit: coef_, intercept_, n_iter_.
2031
+ """
2032
+
2033
+ def __init__(self, *, n_nonzero_coefs=None, fit_intercept=True):
2034
+ self.n_nonzero_coefs, self.fit_intercept = n_nonzero_coefs, fit_intercept
2035
+
2036
+ def fit(self, X, y):
2037
+ import importlib
2038
+ from ._libfind import gramops_backend
2039
+ X, y = fit_xy(self, X, y)
2040
+ Xc, yc, xm, ym = _center(X, y, self.fit_intercept)
2041
+ n, p = Xc.shape
2042
+ k = max(int(0.1 * p), 1) if self.n_nonzero_coefs is None else int(self.n_nonzero_coefs)
2043
+ lib = importlib.import_module(f"{__name__}._generated._loader_gramops_{gramops_backend()}")
2044
+ self.coef_ = np.zeros(p)
2045
+ self.n_iter_ = lib.omp(Xc, yc, self.coef_, np.zeros(1), 0, k, n, p)
2046
+ self.intercept_ = ym - float(xm @ self.coef_)
2047
+ return self
2048
+
2049
+ def predict(self, X):
2050
+ return pred_x(self, X) @ self.coef_ + self.intercept_
2051
+
2052
+
2053
+ _GRAMOPS = []
2054
+
2055
+
2056
+ def _gramops_kernels():
2057
+ # looked up once: several calls a fit, each a glob before
2058
+ if not _GRAMOPS:
2059
+ import importlib
2060
+ from ._libfind import gramops_backend
2061
+ _GRAMOPS.append(importlib.import_module(
2062
+ f"{__name__}._generated._loader_gramops_{gramops_backend()}"))
2063
+ return _GRAMOPS[0]
2064
+
2065
+
2066
+ class LBFGSLogisticRegression(Tagged, ClassifierMixin, BaseEstimator):
2067
+ """L2-penalised logistic regression, scikit-learn's
2068
+ ``LogisticRegression(solver="lbfgs")`` translated whole
2069
+ (``examples/kernel-only/logistic-lbfgs.scm`` over ``lbfgs.scm``):
2070
+ the mean binomial loss for two classes, the multinomial for more,
2071
+ plus |W|^2 / (2 C n), minimised by scipy's L-BFGS-B as written in
2072
+ the subset (ten pairs, the More-Thuente search, gtol ``tol``, ftol
2073
+ 64 eps). The products X W' and R' X are dgemm where a CBLAS links.
2074
+ On the same data it takes the same iterations as scikit-learn and
2075
+ lands on the same coefficients to rounding.
2076
+
2077
+ Attributes after fit: classes_, coef_, intercept_, n_iter_.
2078
+ """
2079
+
2080
+ def __init__(self, *, C=1.0, tol=1e-4, max_iter=100, fit_intercept=True):
2081
+ self.C, self.tol, self.max_iter, self.fit_intercept = C, tol, max_iter, fit_intercept
2082
+
2083
+ def fit(self, X, y):
2084
+ X, y = fit_xy(self, X, y, classifier=True)
2085
+ self.classes_, yi = classes_of(y)
2086
+ n, p = X.shape
2087
+ nc = len(self.classes_)
2088
+ if nc < 2:
2089
+ raise ValueError("This solver needs samples of at least 2 classes in the data, "
2090
+ f"but the data contains only one class: {self.classes_[0]!r}")
2091
+ multi = 1 if nc > 2 else 0
2092
+ k = nc if multi else 1
2093
+ coef = np.zeros(k * (p + 1))
2094
+ out = np.zeros(2)
2095
+ it = _gpu_or_cpu(n * p, getattr(self, "backend", None)).logistic_lbfgs(
2096
+ X, yi.astype(np.float64), coef, out, float(self.C), int(self.max_iter),
2097
+ float(self.tol), multi, 1 if self.fit_intercept else 0, n, p, k)
2098
+ self.coef_ = coef[:k * p].reshape(k, p).copy()
2099
+ self.intercept_ = coef[k * p:].copy()
2100
+ self.n_iter_ = np.array([min(it, self.max_iter)])
2101
+ return self
2102
+
2103
+ def decision_function(self, X):
2104
+ z = pred_x(self, X) @ self.coef_.T + self.intercept_
2105
+ return z[:, 0] if z.shape[1] == 1 else z
2106
+
2107
+ def predict_proba(self, X):
2108
+ z = self.decision_function(X)
2109
+ if z.ndim == 1:
2110
+ p1 = 1.0 / (1.0 + np.exp(-z))
2111
+ return np.column_stack([1.0 - p1, p1])
2112
+ e = np.exp(z - z.max(axis=1, keepdims=True))
2113
+ return e / e.sum(axis=1, keepdims=True)
2114
+
2115
+ def predict(self, X):
2116
+ z = self.decision_function(X)
2117
+ if z.ndim == 1:
2118
+ return self.classes_[(z > 0).astype(int)]
2119
+ return self.classes_[np.argmax(z, axis=1)]
2120
+
2121
+
2122
+ def _kfold(n, k):
2123
+ """scikit-learn's KFold(k) without shuffling: contiguous test blocks,
2124
+ the first n % k of them one longer."""
2125
+ sizes = np.full(k, n // k)
2126
+ sizes[: n % k] += 1
2127
+ out, start = [], 0
2128
+ for sz in sizes:
2129
+ test = np.arange(start, start + sz)
2130
+ out.append((np.r_[np.arange(0, start), np.arange(start + sz, n)], test))
2131
+ start += sz
2132
+ return out
2133
+
2134
+
2135
+ def _stratified_kfold(y, k):
2136
+ """scikit-learn's StratifiedKFold(k) without shuffling: classes in
2137
+ order of first appearance, each spread over the folds as the sorted
2138
+ labels dealt k ways."""
2139
+ y = np.asarray(y)
2140
+ _, y_idx, y_inv = np.unique(y, return_index=True, return_inverse=True)
2141
+ _, class_perm = np.unique(y_idx, return_inverse=True)
2142
+ y_enc = class_perm[y_inv]
2143
+ nc = len(y_idx)
2144
+ y_order = np.sort(y_enc)
2145
+ alloc = np.asarray([np.bincount(y_order[i::k], minlength=nc) for i in range(k)])
2146
+ test_folds = np.empty(len(y), dtype=int)
2147
+ for c in range(nc):
2148
+ test_folds[y_enc == c] = np.arange(k).repeat(alloc[:, c])
2149
+ return [(np.flatnonzero(test_folds != f), np.flatnonzero(test_folds == f))
2150
+ for f in range(k)]
2151
+
2152
+
2153
+ class _LBFGSGLM(Tagged, RegressorMixin, BaseEstimator):
2154
+ _family = None
2155
+
2156
+ def fit(self, X, y):
2157
+ X, y = fit_xy(self, X, y)
2158
+ n, p = X.shape
2159
+ fam, _ = self._family_power()
2160
+ if fam in (0, 2) and (y < 0).any() or fam == 1 and (y <= 0).any():
2161
+ raise ValueError(f"Some value(s) of y are out of the valid range of the loss "
2162
+ f"{type(self).__name__}")
2163
+ coef = np.zeros(p + 1)
2164
+ out = np.zeros(2)
2165
+ fam, power = self._family_power()
2166
+ it = _gpu_or_cpu(n * p, getattr(self, "backend", None)).glm(X, y, coef, out, fam, float(power), float(self.alpha),
2167
+ int(self.max_iter), float(self.tol),
2168
+ 1 if self.fit_intercept else 0, n, p)
2169
+ self.coef_, self.intercept_ = coef[:p].copy(), float(coef[p])
2170
+ self.n_iter_ = min(it, self.max_iter)
2171
+ return self
2172
+
2173
+ def _linear(self, X):
2174
+ return pred_x(self, X) @ self.coef_ + self.intercept_
2175
+
2176
+ def predict(self, X):
2177
+ z = self._linear(X)
2178
+ return z if self._family_power() == (3, 0.0) else np.exp(z)
2179
+
2180
+
2181
+ class LBFGSPoissonRegressor(_LBFGSGLM):
2182
+ _positive_y = True
2183
+
2184
+ """scikit-learn's ``PoissonRegressor`` (solver "lbfgs") translated
2185
+ whole (``examples/kernel-only/glm.scm`` over ``lbfgs.scm``): the mean
2186
+ half Poisson deviance with the log link plus alpha |w|^2 / 2, from
2187
+ scikit-learn's start. Same iterations and coefficients to rounding.
2188
+
2189
+ Attributes after fit: coef_, intercept_, n_iter_.
2190
+ """
2191
+
2192
+ def __init__(self, *, alpha=1.0, fit_intercept=True, max_iter=100, tol=1e-4):
2193
+ self.alpha, self.fit_intercept, self.max_iter, self.tol = alpha, fit_intercept, max_iter, tol
2194
+
2195
+ def _family_power(self):
2196
+ return 0, 1.0
2197
+
2198
+
2199
+ class LBFGSGammaRegressor(LBFGSPoissonRegressor):
2200
+ """scikit-learn's ``GammaRegressor`` (solver "lbfgs"), as
2201
+ LBFGSPoissonRegressor with the half Gamma deviance.
2202
+
2203
+ Attributes after fit: coef_, intercept_, n_iter_.
2204
+ """
2205
+
2206
+ def _family_power(self):
2207
+ return 1, 2.0
2208
+
2209
+
2210
+ class LBFGSTweedieRegressor(_LBFGSGLM):
2211
+ """scikit-learn's ``TweedieRegressor`` (solver "lbfgs"): ``power`` 0
2212
+ with the identity link (the default), or a power of 1 or more with
2213
+ the log link, as link="auto" chooses.
2214
+
2215
+ Attributes after fit: coef_, intercept_, n_iter_.
2216
+ """
2217
+
2218
+ def __init__(self, *, power=0.0, alpha=1.0, fit_intercept=True, max_iter=100, tol=1e-4):
2219
+ self.power, self.alpha, self.fit_intercept = power, alpha, fit_intercept
2220
+ self.max_iter, self.tol = max_iter, tol
2221
+
2222
+ def _family_power(self):
2223
+ if self.power == 0:
2224
+ return 3, 0.0
2225
+ if self.power < 1:
2226
+ raise ValueError("power is 0 or at least 1 here")
2227
+ return 2, float(self.power)
2228
+
2229
+
2230
+ class LBFGSLogisticRegressionCV(Tagged, ClassifierMixin, BaseEstimator):
2231
+ """scikit-learn's ``LogisticRegressionCV`` with its defaults (the L2
2232
+ penalty, solver "lbfgs", Cs 10 values from 1e-4 to 1e4,
2233
+ StratifiedKFold(5) without shuffling, accuracy, refit): each fold's
2234
+ path over the Cs warm-started from the previous C by the translated
2235
+ LogisticRegression (``logistic-lbfgs.scm``), the C of the best summed
2236
+ score, and the refit from the folds' mean coefficients at that C, as
2237
+ scikit-learn starts it.
2238
+
2239
+ Attributes after fit: classes_, Cs_, C_, coef_, intercept_, scores_,
2240
+ n_iter_.
2241
+ """
2242
+
2243
+ def __init__(self, *, Cs=10, cv=5, tol=1e-4, max_iter=100, fit_intercept=True):
2244
+ self.Cs, self.cv, self.tol, self.max_iter = Cs, cv, tol, max_iter
2245
+ self.fit_intercept = fit_intercept
2246
+
2247
+ def _path(self, X, yi, Cs, coef, multi, k):
2248
+ n, p = X.shape
2249
+ lib = _gpu_or_cpu(n * p, getattr(self, "backend", None))
2250
+ coefs, iters = [], []
2251
+ out = np.zeros(2)
2252
+ for C in Cs:
2253
+ it = lib.logistic_lbfgs(X, yi, coef, out, float(C), int(self.max_iter),
2254
+ float(self.tol), multi, 1 if self.fit_intercept else 0,
2255
+ n, p, k)
2256
+ coefs.append(coef.copy())
2257
+ iters.append(min(it, self.max_iter))
2258
+ return coefs, iters
2259
+
2260
+ def fit(self, X, y):
2261
+ X, y = fit_xy(self, X, y, classifier=True)
2262
+ self.classes_, yi = classes_of(y)
2263
+ nc = len(self.classes_)
2264
+ if nc < 2:
2265
+ raise ValueError("This solver needs samples of at least 2 classes in the data, "
2266
+ f"but the data contains only one class: {self.classes_[0]!r}")
2267
+ multi = 1 if nc > 2 else 0
2268
+ k = nc if multi else 1
2269
+ n, p = X.shape
2270
+ Cs = (np.logspace(-4, 4, int(self.Cs)) if np.isscalar(self.Cs)
2271
+ else np.asarray(self.Cs, float))
2272
+ self.Cs_ = Cs
2273
+ yf = yi.astype(np.float64)
2274
+ folds = _stratified_kfold(y, int(self.cv))
2275
+ paths, scores, iters = [], [], []
2276
+ for train, test in folds:
2277
+ coefs, it = self._path(np.ascontiguousarray(X[train]), yf[train], Cs,
2278
+ np.zeros(k * (p + 1)), multi, k)
2279
+ paths.append(coefs)
2280
+ iters.append(it)
2281
+ sc = []
2282
+ for c in coefs:
2283
+ z = X[test] @ c[:k * p].reshape(k, p).T + c[k * p:]
2284
+ pred = (z[:, 0] > 0).astype(int) if k == 1 else np.argmax(z, axis=1)
2285
+ sc.append(float(np.mean(pred == yi[test])))
2286
+ scores.append(sc)
2287
+ scores = np.asarray(scores)
2288
+ best = int(np.argmax(scores.sum(axis=0)))
2289
+ self.C_ = float(Cs[best])
2290
+ start = np.mean([paths[f][best] for f in range(len(folds))], axis=0)
2291
+ coefs, it = self._path(X, yf, [self.C_], start.copy(), multi, k)
2292
+ c = coefs[0]
2293
+ self.coef_ = c[:k * p].reshape(k, p).copy()
2294
+ self.intercept_ = c[k * p:].copy()
2295
+ self.scores_ = scores
2296
+ self.n_iter_ = np.asarray(iters)
2297
+ return self
2298
+
2299
+ def decision_function(self, X):
2300
+ z = pred_x(self, X) @ self.coef_.T + self.intercept_
2301
+ return z[:, 0] if z.shape[1] == 1 else z
2302
+
2303
+ def predict(self, X):
2304
+ z = self.decision_function(X)
2305
+ if z.ndim == 1:
2306
+ return self.classes_[(z > 0).astype(int)]
2307
+ return self.classes_[np.argmax(z, axis=1)]
2308
+
2309
+
2310
+ class LBFGSHuberRegressor(Tagged, RegressorMixin, BaseEstimator):
2311
+ """The Huber regressor, scikit-learn's ``HuberRegressor`` translated
2312
+ whole (``examples/kernel-only/huber.scm`` over ``lbfgs.scm``): its
2313
+ _huber_loss_and_gradient over the weights, the intercept and the
2314
+ scale, minimised by L-BFGS-B with the scale bounded below by 10 eps
2315
+ (the generalized Cauchy point and the subspace step for that one
2316
+ bound, as L-BFGS-B takes them), scipy's defaults otherwise. X w
2317
+ and X'c are dgemv where a CBLAS links. Same iterations and
2318
+ coefficients as scikit-learn to rounding.
2319
+
2320
+ Attributes after fit: coef_, intercept_, scale_, n_iter_, outliers_.
2321
+ """
2322
+
2323
+ def __init__(self, *, epsilon=1.35, alpha=1e-4, max_iter=100, tol=1e-5,
2324
+ fit_intercept=True):
2325
+ self.epsilon, self.alpha, self.max_iter, self.tol = epsilon, alpha, max_iter, tol
2326
+ self.fit_intercept = fit_intercept
2327
+
2328
+ def fit(self, X, y):
2329
+ X, y = fit_xy(self, X, y)
2330
+ n, p = X.shape
2331
+ coef = np.zeros(p + 2)
2332
+ coef[-1] = 1.0
2333
+ out = np.zeros(2)
2334
+ it = _gpu_or_cpu(n * p, getattr(self, "backend", None)).huber(
2335
+ X, y, coef, out, float(self.epsilon), float(self.alpha), int(self.max_iter),
2336
+ float(self.tol), 1 if self.fit_intercept else 0, n, p)
2337
+ self.coef_ = coef[:p].copy()
2338
+ self.intercept_ = float(coef[p])
2339
+ self.scale_ = float(coef[p + 1])
2340
+ self.n_iter_ = min(it, self.max_iter)
2341
+ self.outliers_ = np.abs(y - X @ self.coef_ - self.intercept_) > self.scale_ * self.epsilon
2342
+ return self
2343
+
2344
+ def predict(self, X):
2345
+ return pred_x(self, X) @ self.coef_ + self.intercept_
2346
+
2347
+
2348
+ class EMGaussianMixture(Tagged, DensityMixin, BaseEstimator):
2349
+ """The Gaussian mixture by EM with full covariances, scikit-learn's
2350
+ ``GaussianMixture(covariance_type="full")`` translated whole
2351
+ (``examples/kernel-only/gmm.scm``): its M step (means and
2352
+ covariances by products, the Cholesky factor, the precision factor
2353
+ L^-T), its E step (the log densities through X U - mu U, a product;
2354
+ log-sum-exp; the lower bound) and its stop on the bound. The start
2355
+ is scikit-learn's: ``init_params="kmeans"`` takes the labels of
2356
+ ``KMeans(n_init=1)`` (scikit-learn's, so it must be installed) drawn
2357
+ from ``RandomState(random_state)``, ``"random"`` uniform draws
2358
+ normalised; with the same ``random_state`` the fit is
2359
+ scikit-learn's to rounding. One initialisation (n_init=1).
2360
+
2361
+ Attributes after fit: weights_, means_, precisions_cholesky_,
2362
+ precisions_, covariances_, converged_, n_iter_, lower_bound_.
2363
+ """
2364
+
2365
+ def __init__(self, n_components=1, *, tol=1e-3, reg_covar=1e-6, max_iter=100,
2366
+ init_params="kmeans", random_state=None):
2367
+ self.n_components, self.tol, self.reg_covar = n_components, tol, reg_covar
2368
+ self.max_iter, self.init_params, self.random_state = max_iter, init_params, random_state
2369
+
2370
+ def fit(self, X, y=None):
2371
+ X = fit_x(self, X, ensure_min_samples=2)
2372
+ n, p = X.shape
2373
+ k = int(self.n_components)
2374
+ if k > n:
2375
+ raise ValueError(f"Expected n_samples >= n_components but got n_components = {k}, "
2376
+ f"n_samples = {n}")
2377
+ rs = np.random.RandomState(self.random_state)
2378
+ if self.init_params == "kmeans":
2379
+ try:
2380
+ from sklearn.cluster import KMeans
2381
+ except ImportError as e:
2382
+ raise ImportError("init_params='kmeans' runs scikit-learn's KMeans; "
2383
+ "install scikit-learn or pass init_params='random'") from e
2384
+ labels = KMeans(n_clusters=k, n_init=1, random_state=rs).fit(X).labels_
2385
+ resp = np.zeros((n, k))
2386
+ resp[np.arange(n), labels] = 1.0
2387
+ elif self.init_params == "random":
2388
+ resp = rs.uniform(size=(n, k))
2389
+ resp /= resp.sum(axis=1)[:, None]
2390
+ else:
2391
+ raise ValueError("init_params is 'kmeans' or 'random'")
2392
+ resp = np.ascontiguousarray(resp)
2393
+ self.weights_ = np.zeros(k)
2394
+ self.means_ = np.zeros((k, p))
2395
+ self.precisions_cholesky_ = np.zeros((k, p, p))
2396
+ labels = np.zeros(n)
2397
+ out = np.zeros(2)
2398
+ it = _gpu_or_cpu(n * p, getattr(self, "backend", None)).gmm(X, resp, self.weights_, self.means_,
2399
+ self.precisions_cholesky_, labels, out,
2400
+ int(self.max_iter), float(self.tol),
2401
+ float(self.reg_covar), n, p, k)
2402
+ self.n_iter_ = it
2403
+ self.lower_bound_ = float(out[0])
2404
+ self.converged_ = bool(out[1] == 1.0)
2405
+ self.precisions_ = np.einsum("kij,klj->kil", self.precisions_cholesky_,
2406
+ self.precisions_cholesky_)
2407
+ self.covariances_ = np.linalg.inv(self.precisions_)
2408
+ return self
2409
+
2410
+ def _weighted_log_prob(self, X):
2411
+ X = pred_x(self, X)
2412
+ n, p = X.shape
2413
+ out = np.empty((n, len(self.weights_)))
2414
+ for c, (mu, u) in enumerate(zip(self.means_, self.precisions_cholesky_)):
2415
+ y = X @ u - mu @ u
2416
+ out[:, c] = (-0.5 * (p * np.log(2 * np.pi) + (y * y).sum(axis=1))
2417
+ + np.log(np.diag(u)).sum() + np.log(self.weights_[c]))
2418
+ return out
2419
+
2420
+ def predict_proba(self, X):
2421
+ w = self._weighted_log_prob(X)
2422
+ w -= w.max(axis=1, keepdims=True)
2423
+ e = np.exp(w)
2424
+ return e / e.sum(axis=1, keepdims=True)
2425
+
2426
+ def predict(self, X):
2427
+ return np.argmax(self._weighted_log_prob(X), axis=1)
2428
+
2429
+ def fit_predict(self, X, y=None):
2430
+ return self.fit(X).predict(X)
2431
+
2432
+ def score_samples(self, X):
2433
+ """The log density of each row under the mixture."""
2434
+ w = self._weighted_log_prob(X)
2435
+ m = w.max(axis=1)
2436
+ return m + np.log(np.exp(w - m[:, None]).sum(axis=1))
2437
+
2438
+ def score(self, X, y=None):
2439
+ """The mean log-likelihood, as GaussianMixture.score."""
2440
+ return float(self.score_samples(X).mean())
2441
+
2442
+
2443
+ class CovPCA(Tagged, TransformerMixin, BaseEstimator):
2444
+ """PCA through the covariance's eigenvectors, scikit-learn's
2445
+ ``PCA(svd_solver="covariance_eigh")`` -- what its "auto" picks for a
2446
+ tall design (p <= 1000, n >= 10 p) -- translated whole
2447
+ (``examples/kernel-only/pca.scm``: X'X by dsyrk where a CBLAS links,
2448
+ the eigenproblem by sym-eigen.scm -- which the BLAS build hands to
2449
+ LAPACK's dsyevd, as numpy's eigh does, and the loop build runs as
2450
+ Householder reduction and QL iteration in the subset -- and
2451
+ svd_flip's signs). The BLAS build is level with scikit-learn on one
2452
+ core at 50,000 x 500 and with sklearnex on twenty; the loop build's
2453
+ eigensolver falls behind LAPACK's from about a hundred features.
2454
+
2455
+ Attributes after fit: components_, explained_variance_,
2456
+ explained_variance_ratio_, singular_values_, mean_, noise_variance_,
2457
+ n_components_.
2458
+ """
2459
+
2460
+ def __init__(self, n_components=None, *, backend=None):
2461
+ self.n_components, self.backend = n_components, backend
2462
+
2463
+ def fit(self, X, y=None):
2464
+ X = fit_x(self, X)
2465
+ n, p = X.shape
2466
+ if self.n_components is not None and not 0 <= int(self.n_components) <= min(n, p):
2467
+ raise ValueError(f"n_components={self.n_components!r} must be between 0 and "
2468
+ f"min(n_samples, n_features)={min(n, p)}")
2469
+ comps = np.zeros((p, p)); ev = np.zeros(p); sv = np.zeros(p); mean = np.zeros(p)
2470
+ # the device forms the covariance faster, but its build keeps
2471
+ # sym-eigen.scm's eigensolver; where the CPU build has LAPACK's
2472
+ # (gramops "blas") that is the faster whole, so the device is
2473
+ # taken by default only without it
2474
+ from ._libfind import gramops_backend
2475
+ dev = self.backend == "cublas" or (self.backend is None and gramops_backend() != "blas")
2476
+ lib = _accel(float(n) * p * p) if dev else None
2477
+ (lib or _gramops_kernels()).pca(X, comps, ev, sv, mean, n, p)
2478
+ k = min(n, p) if self.n_components is None else int(self.n_components)
2479
+ self.n_components_ = k
2480
+ self.mean_ = mean
2481
+ self.components_ = comps[:k].copy()
2482
+ self.explained_variance_ = ev[:k].copy()
2483
+ tot = ev.sum()
2484
+ self.explained_variance_ratio_ = ev[:k] / tot if tot > 0 else np.zeros(k)
2485
+ self.singular_values_ = sv[:k].copy()
2486
+ self.noise_variance_ = float(ev[k:].mean()) if k < min(n, p) else 0.0
2487
+ return self
2488
+
2489
+ def transform(self, X):
2490
+ return (pred_x(self, X) - self.mean_) @ self.components_.T
2491
+
2492
+ def fit_transform(self, X, y=None):
2493
+ return self.fit(X).transform(X)
2494
+
2495
+
2496
+ _KPCA_KERNELS = {"linear": 0, "rbf": 1, "poly": 2, "sigmoid": 3, "cosine": 4}
2497
+
2498
+
2499
+ def _psd_eigenvalues(vals):
2500
+ # scikit-learn's _check_psd_eigenvalues (double precision): refuse
2501
+ # a matrix far from PSD, zero the small negative and positive noise
2502
+ vals = np.array(vals, dtype=np.float64)
2503
+ top = vals.max() if vals.size else 0.0
2504
+ if top < 0:
2505
+ raise ValueError(f"All eigenvalues are negative (maximum is {top:g}). Either the "
2506
+ "matrix is not PSD, or there was an issue while computing the "
2507
+ "eigendecomposition of the matrix.")
2508
+ low = vals.min() if vals.size else 0.0
2509
+ if low < -1e-5 * top and low < -1e-10:
2510
+ raise ValueError(f"There are significant negative eigenvalues ({-low / top:g} of the "
2511
+ "maximum positive). Either the matrix is not PSD, or there was an "
2512
+ "issue while computing the eigendecomposition of the matrix.")
2513
+ vals[vals < 0] = 0.0
2514
+ vals[vals < 1e-12 * top] = 0.0
2515
+ return vals
2516
+
2517
+
2518
+ class GramKernelPCA(Tagged, TransformerMixin, BaseEstimator):
2519
+ """scikit-learn's ``KernelPCA``: the kernel matrix (linear, rbf,
2520
+ poly, sigmoid, cosine or precomputed), centred in feature space, its
2521
+ largest eigenpairs with svd_flip's signs (``examples/kernel-only/
2522
+ kernel-pca.scm``). Three routes to the eigenpairs:
2523
+
2524
+ - the linear kernel with n_components <= p < n: through Xc'Xc
2525
+ (p x p, X'X by dsyrk), O(n p^2) instead of the n x n matrix;
2526
+ - a few pairs of a large matrix (``eigen_solver="auto"``, where
2527
+ scikit-learn takes ARPACK, and ``"subspace"``): subspace iteration
2528
+ whose product is a dgemm, stopped when every residual
2529
+ |K u - lam u| is under ``tol`` (1e-12 for 0) of the largest value,
2530
+ the dense route when it does not converge in ``max_iter`` steps;
2531
+ - otherwise dense: LAPACK's dsyevr over the wanted index range, as
2532
+ scipy's eigh(subset_by_index) that scikit-learn calls.
2533
+
2534
+ No inverse transform. Attributes after fit: eigenvalues_,
2535
+ eigenvectors_, X_fit_, gamma_, n_iter_ (the subspace steps, 1 for a
2536
+ direct solve), n_features_in_.
2537
+ """
2538
+
2539
+ def __init__(self, n_components=None, *, kernel="linear", gamma=None, degree=3, coef0=1,
2540
+ eigen_solver="auto", tol=0, max_iter=None, remove_zero_eig=False,
2541
+ random_state=None):
2542
+ self.n_components, self.kernel, self.gamma = n_components, kernel, gamma
2543
+ self.degree, self.coef0, self.eigen_solver = degree, coef0, eigen_solver
2544
+ self.tol, self.max_iter, self.remove_zero_eig = tol, max_iter, remove_zero_eig
2545
+ self.random_state = random_state
2546
+
2547
+ def _kernel(self, A, B):
2548
+ k = _gramops_kernels()
2549
+ if B is None:
2550
+ K = np.zeros((A.shape[0], A.shape[0]))
2551
+ k.kpca_kernel_self(A, K, self._kind, self.gamma_, float(self.degree),
2552
+ float(self.coef0), A.shape[0], A.shape[1])
2553
+ else:
2554
+ K = np.zeros((A.shape[0], B.shape[0]))
2555
+ k.kpca_kernel(A, B, K, self._kind, self.gamma_, float(self.degree),
2556
+ float(self.coef0), A.shape[0], B.shape[0], A.shape[1])
2557
+ return K
2558
+
2559
+ def fit(self, X, y=None):
2560
+ X = fit_x(self, X)
2561
+ n, p = X.shape
2562
+ if self.kernel != "precomputed" and self.kernel not in _KPCA_KERNELS:
2563
+ raise ValueError(f"kernel={self.kernel!r}: expected one of "
2564
+ f"{sorted(_KPCA_KERNELS) + ['precomputed']}")
2565
+ if self.eigen_solver not in ("auto", "dense", "subspace"):
2566
+ raise ValueError(f"eigen_solver={self.eigen_solver!r}: expected 'auto', 'dense' "
2567
+ "or 'subspace'")
2568
+ if self.n_components is not None and int(self.n_components) < 1:
2569
+ raise ValueError(f"n_components={self.n_components!r} must be at least 1")
2570
+ if self.kernel == "precomputed" and n != p:
2571
+ raise ValueError(f"precomputed kernel is {n} x {p}; expected a square matrix")
2572
+ self._kind = _KPCA_KERNELS.get(self.kernel, -1)
2573
+ self.gamma_ = 1.0 / p if self.gamma is None else float(self.gamma)
2574
+ c = n if self.n_components is None else min(n, int(self.n_components))
2575
+ k = _gramops_kernels()
2576
+ vecs, vals = np.zeros((n, c)), np.zeros(c)
2577
+ m = np.zeros(n + 1)
2578
+ self.n_iter_ = 1
2579
+ if self.kernel == "linear" and c <= p < n:
2580
+ xm = X.mean(axis=0)
2581
+ G = _gram(X)
2582
+ nm2 = n * xm * xm
2583
+ if np.all(np.diagonal(G) - nm2 > 1e-4 * nm2):
2584
+ G -= np.outer(xm, n * xm)
2585
+ Xs, xs = X, xm
2586
+ else:
2587
+ Xs, xs = np.ascontiguousarray(X - xm), np.zeros(p)
2588
+ G = _gram(Xs)
2589
+ k.kpca_linear(Xs, xs, np.ascontiguousarray(G), vecs, vals, n, p, c)
2590
+ # KernelCenterer's statistics of K = X X', for transform
2591
+ m[:n] = X @ xm
2592
+ m[n] = float(xm @ xm)
2593
+ else:
2594
+ K = np.array(X, dtype=np.float64, order="C") if self.kernel == "precomputed" \
2595
+ else self._kernel(X, None)
2596
+ k.kpca_centre(K, m, n)
2597
+ # c + 25 columns: on an rbf kernel whose leading values fall
2598
+ # slowly (0.92 of the first by the fifth), 13 took 235 steps
2599
+ # to 1e-12 and 30 took 15
2600
+ b = min(n, max(2 * c, c + 25))
2601
+ # where scikit-learn's "auto" takes ARPACK; for 50 components
2602
+ # of 3,000 the 100 columns lost to dsyevr (6.2 s to 3.6 s)
2603
+ sub = self.eigen_solver == "subspace" or (
2604
+ self.eigen_solver == "auto" and n > 200 and c < 10)
2605
+ done = False
2606
+ if sub and b < n:
2607
+ rs = self.random_state
2608
+ rng = rs if isinstance(rs, np.random.RandomState) else \
2609
+ np.random.RandomState(0 if rs is None else int(rs))
2610
+ Q = rng.standard_normal((n, b))
2611
+ tol = float(self.tol) if float(self.tol) > 0 else 1e-12
2612
+ it = 1000 if self.max_iter is None else int(self.max_iter)
2613
+ steps = k.kpca_top_subspace(K, Q, vecs, vals, n, b, c, tol, it)
2614
+ done = steps >= 0
2615
+ if done:
2616
+ self.n_iter_ = steps
2617
+ if not done:
2618
+ k.kpca_top_dense(K, vecs, vals, n, c)
2619
+ vals = _psd_eigenvalues(vals)
2620
+ if self.remove_zero_eig or self.n_components is None:
2621
+ keep = vals > 0
2622
+ vecs, vals = vecs[:, keep], vals[keep]
2623
+ self.eigenvalues_ = vals
2624
+ self.eigenvectors_ = np.ascontiguousarray(vecs)
2625
+ self.X_fit_ = X
2626
+ self._m = m
2627
+ return self
2628
+
2629
+ def fit_transform(self, X, y=None):
2630
+ self.fit(X)
2631
+ return self.eigenvectors_ * np.sqrt(self.eigenvalues_)
2632
+
2633
+ def transform(self, X):
2634
+ X = pred_x(self, X)
2635
+ n = self.X_fit_.shape[0]
2636
+ if self.kernel == "precomputed":
2637
+ if X.shape[1] != n:
2638
+ raise ValueError(f"precomputed kernel has {X.shape[1]} columns; expected {n}")
2639
+ K = np.array(X, dtype=np.float64, order="C")
2640
+ else:
2641
+ K = self._kernel(X, self.X_fit_)
2642
+ _gramops_kernels().kpca_centre_new(K, self._m, K.shape[0], n)
2643
+ nz = self.eigenvalues_ > 0
2644
+ scaled = np.zeros_like(self.eigenvectors_)
2645
+ scaled[:, nz] = self.eigenvectors_[:, nz] / np.sqrt(self.eigenvalues_[nz])
2646
+ return K @ scaled
2647
+
2648
+
2649
+ def _lda_svd_dof(n, K):
2650
+ # the divisor of LinearDiscriminantAnalysis's svd solver: n from
2651
+ # scikit-learn 1.9.1, n - K before; n without scikit-learn
2652
+ try:
2653
+ import sklearn
2654
+ v = tuple(int(x) for x in sklearn.__version__.split(".")[:3] if x.isdigit())
2655
+ except Exception:
2656
+ return n
2657
+ return n - K if v < (1, 9, 1) else n
2658
+
2659
+
2660
+ class GramLDA(Tagged, ClassifierMixin, TransformerMixin, BaseEstimator):
2661
+ """scikit-learn's ``LinearDiscriminantAnalysis`` over the Gram matrix
2662
+ (``examples/kernel-only/lda.scm``): X'X by dsyrk and the class means
2663
+ in one pass, then the three solvers' own steps on p x p matrices --
2664
+ ``"svd"`` (the default) takes its first SVD, of the n x p
2665
+ standardised within-class design, as the eigenproblem of
2666
+ D^-1 Sw D^-1 (dsyevd); ``"lsqr"`` solves Sw W = M' by Cholesky;
2667
+ ``"eigen"`` is Sb v = lam Sw v (dsygvd). ``shrinkage`` takes None or a
2668
+ float (not "auto"); no ``covariance_estimator``.
2669
+
2670
+ Attributes after fit: classes_, coef_, intercept_, means_, priors_,
2671
+ covariance_ (lsqr, eigen, or store_covariance), scalings_ and
2672
+ explained_variance_ratio_ (svd, eigen), xbar_ (svd), n_features_in_.
2673
+ """
2674
+
2675
+ def __init__(self, solver="svd", shrinkage=None, priors=None, n_components=None,
2676
+ store_covariance=False, tol=1e-4):
2677
+ self.solver, self.shrinkage, self.priors = solver, shrinkage, priors
2678
+ self.n_components, self.store_covariance, self.tol = n_components, store_covariance, tol
2679
+
2680
+ @staticmethod
2681
+ def _shrunk(C, s):
2682
+ # shrunk_covariance: (1 - s) C + s tr(C) / p I
2683
+ if s is None:
2684
+ return C
2685
+ p = C.shape[0]
2686
+ out = (1.0 - s) * C
2687
+ out.flat[::p + 1] += s * np.trace(C) / p
2688
+ return out
2689
+
2690
+ def fit(self, X, y):
2691
+ if self.solver not in ("svd", "lsqr", "eigen"):
2692
+ raise ValueError(f"solver={self.solver!r}: expected 'svd', 'lsqr' or 'eigen'")
2693
+ s = self.shrinkage
2694
+ if s is not None and (isinstance(s, str) or not 0.0 <= float(s) <= 1.0):
2695
+ raise ValueError(f"shrinkage={s!r}: GramLDA takes None or a float in [0, 1]")
2696
+ if self.solver == "svd" and s is not None:
2697
+ raise NotImplementedError("shrinkage not supported with 'svd' solver.")
2698
+ s = None if s is None else float(s)
2699
+ X, y = fit_xy(self, X, y, classifier=True)
2700
+ n, p = X.shape
2701
+ if n < 2:
2702
+ raise ValueError(f"Found array with {n} sample(s) (shape={X.shape}) while a "
2703
+ "minimum of 2 is required.")
2704
+ self.classes_, yi = classes_of(y)
2705
+ K = len(self.classes_)
2706
+ if n == K:
2707
+ raise ValueError("The number of samples must be more than the number of classes.")
2708
+ if K < 2:
2709
+ raise ValueError("The number of classes has to be greater than one; got 1 class")
2710
+ k = _gramops_kernels()
2711
+ lab = np.ascontiguousarray(yi, dtype=np.int32)
2712
+ G, means, counts = np.zeros((p, p)), np.zeros((K, p)), np.zeros(K)
2713
+ k.lda_moments(X, lab, G, means, counts, n, p, K)
2714
+ if self.priors is None:
2715
+ priors = counts / n
2716
+ else:
2717
+ priors = np.asarray(self.priors, dtype=np.float64)
2718
+ if np.any(priors < 0):
2719
+ raise ValueError("priors must be non-negative")
2720
+ if abs(priors.sum() - 1.0) > 1e-5:
2721
+ warnings.warn("The priors do not sum to 1. Renormalizing", UserWarning)
2722
+ priors = priors / priors.sum()
2723
+ self.priors_, self.means_ = priors, means
2724
+ top = min(K - 1, p)
2725
+ if self.n_components is not None and int(self.n_components) > top:
2726
+ raise ValueError("n_components cannot be larger than min(n_features, n_classes - 1).")
2727
+ self._max_components = top if self.n_components is None else int(self.n_components)
2728
+ xx = np.diagonal(G).copy()
2729
+ k.lda_within(G, means, counts, n, p, K) # G is now Sw, empirical priors
2730
+ if not np.all(np.diagonal(G) > 1e-8 * xx / n):
2731
+ # a column whose class means dwarf its spread: the correction
2732
+ # cancelled its digits, so take the centred rows instead
2733
+ Xc = np.ascontiguousarray(X - means[yi])
2734
+ G = _gram(Xc) / n
2735
+ Sw_emp = G
2736
+
2737
+ def class_cov():
2738
+ # scikit-learn's _class_cov: sum_k prior_k (shrunk) C_k; with
2739
+ # the empirical priors that is the shrunk Sw, else per class
2740
+ if self.priors is None or np.allclose(priors, counts / n):
2741
+ return self._shrunk(Sw_emp, s)
2742
+ C = np.zeros((p, p))
2743
+ for c in range(K):
2744
+ Xk = np.ascontiguousarray(X[yi == c] - means[c])
2745
+ C += priors[c] * self._shrunk(_gram(Xk) / max(Xk.shape[0], 1), s)
2746
+ return C
2747
+
2748
+ if self.solver == "svd":
2749
+ if self.store_covariance:
2750
+ self.covariance_ = class_cov()
2751
+ self.xbar_ = priors @ means
2752
+ std, V, S = np.zeros(p), np.zeros((p, p)), np.zeros(p)
2753
+ k.lda_svd_first(np.ascontiguousarray(Sw_emp), std, V, S, p)
2754
+ # S is the SVD of Xc D^-1 / sqrt(n); scikit-learn before 1.9.1
2755
+ # divides by sqrt(n - K) instead (#33626), and its tol and
2756
+ # scalings_ see that scale
2757
+ S *= np.sqrt(n / _lda_svd_dof(n, K))
2758
+ rank = int(np.sum(S > self.tol))
2759
+ scal = (V[:, :rank] / std[:, None]) / S[:rank]
2760
+ fac = 1.0 if K == 1 else 1.0 / (K - 1)
2761
+ Z = (np.sqrt(n * priors * fac) * (means - self.xbar_).T).T @ scal
2762
+ _, S2, Vt2 = np.linalg.svd(Z, full_matrices=False)
2763
+ self.explained_variance_ratio_ = (S2 ** 2 / np.sum(S2 ** 2))[:self._max_components] \
2764
+ if self._max_components else np.empty((0,))
2765
+ rank2 = int(np.sum(S2 > self.tol * S2[0]))
2766
+ self.scalings_ = scal @ Vt2.T[:, :rank2]
2767
+ coef = (means - self.xbar_) @ self.scalings_
2768
+ self.intercept_ = -0.5 * np.sum(coef ** 2, axis=1) + np.log(priors)
2769
+ self.coef_ = coef @ self.scalings_.T
2770
+ self.intercept_ -= self.xbar_ @ self.coef_.T
2771
+ else:
2772
+ Sw = class_cov()
2773
+ self.covariance_ = Sw
2774
+ if self.solver == "lsqr":
2775
+ coef = _ridge_solve(Sw, np.ascontiguousarray(means.T), 0.0)
2776
+ if coef is None:
2777
+ coef = np.linalg.lstsq(Sw, means.T, rcond=None)[0]
2778
+ self.coef_ = coef.T
2779
+ self.intercept_ = -0.5 * np.diag(means @ self.coef_.T) + np.log(priors)
2780
+ else:
2781
+ xbar = counts @ means / n
2782
+ St = self._shrunk(Sw_emp + (means - xbar).T @ ((counts / n)[:, None] * (means - xbar)), s)
2783
+ V, ev = np.zeros((p, p)), np.zeros(p)
2784
+ k.lda_eigen(np.ascontiguousarray(St - Sw), np.ascontiguousarray(Sw.copy()), V, ev, p)
2785
+ self.explained_variance_ratio_ = (ev / np.sum(ev))[:self._max_components]
2786
+ self.scalings_ = V
2787
+ self.coef_ = means @ V @ V.T
2788
+ self.intercept_ = -0.5 * np.diag(means @ self.coef_.T) + np.log(priors)
2789
+ if K == 2:
2790
+ self.coef_ = (self.coef_[1, :] - self.coef_[0, :]).reshape(1, -1)
2791
+ self.intercept_ = np.asarray(self.intercept_[1] - self.intercept_[0]).reshape(1)
2792
+ return self
2793
+
2794
+ def decision_function(self, X):
2795
+ check_is_fitted(self)
2796
+ d = pred_x(self, X) @ self.coef_.T + self.intercept_
2797
+ return d.ravel() if d.shape[1] == 1 else d
2798
+
2799
+ def predict(self, X):
2800
+ d = self.decision_function(X)
2801
+ idx = (d > 0).astype(int) if d.ndim == 1 else d.argmax(axis=1)
2802
+ return self.classes_[idx]
2803
+
2804
+ def predict_proba(self, X):
2805
+ d = self.decision_function(X)
2806
+ if d.ndim == 1:
2807
+ p1 = 1.0 / (1.0 + np.exp(-d))
2808
+ return np.stack([1 - p1, p1], axis=1)
2809
+ e = np.exp(d - d.max(axis=1, keepdims=True))
2810
+ return e / e.sum(axis=1, keepdims=True)
2811
+
2812
+ def predict_log_proba(self, X):
2813
+ P = self.predict_proba(X)
2814
+ with np.errstate(divide="ignore"):
2815
+ return np.log(P)
2816
+
2817
+ def transform(self, X):
2818
+ if self.solver == "lsqr":
2819
+ raise NotImplementedError(
2820
+ "transform not implemented for 'lsqr' solver (use 'svd' or 'eigen').")
2821
+ check_is_fitted(self)
2822
+ X = pred_x(self, X)
2823
+ Xn = (X - self.xbar_) @ self.scalings_ if self.solver == "svd" else X @ self.scalings_
2824
+ return Xn[:, :self._max_components]
2825
+
2826
+
2827
+ class GramTruncatedSVD(Tagged, TransformerMixin, BaseEstimator):
2828
+ """scikit-learn's ``TruncatedSVD`` on a dense X, through the Gram
2829
+ matrix (``examples/kernel-only/truncated-svd.scm``): the leading
2830
+ ``n_components`` pairs of X'X (n >= p; X'X by dsyrk) or of X X'
2831
+ (wide) by dsyevr over the wanted index range, the transformed data
2832
+ by one dgemm, svd_flip's signs (u_based_decision=False).
2833
+
2834
+ The result is the exact truncated SVD, what ``algorithm="arpack"``
2835
+ computes; scikit-learn's default randomized solver approximates it
2836
+ (5 power iterations), so against that one the components agree to
2837
+ its approximation error. ``algorithm``, ``n_iter``,
2838
+ ``n_oversamples``, ``power_iteration_normalizer``, ``random_state``
2839
+ and ``tol`` are taken for the interface and do not change the
2840
+ answer. A scipy.sparse X (TruncatedSVD's usual input, latent
2841
+ semantic analysis) goes the same way: X'X (or X X') by csr-gram,
2842
+ its leading pairs by dsyevr, X V by csr-mm; no centring, as in
2843
+ scikit-learn. The Gram is min(n, p) square, so a sparse X with
2844
+ both sides in the hundreds of thousands is beyond it.
2845
+
2846
+ Attributes after fit: components_, explained_variance_,
2847
+ explained_variance_ratio_, singular_values_, n_features_in_.
2848
+ """
2849
+ _sparse = True
2850
+
2851
+ def __init__(self, n_components=2, *, algorithm="randomized", n_iter=5, n_oversamples=10,
2852
+ power_iteration_normalizer="auto", random_state=None, tol=0.0):
2853
+ self.n_components, self.algorithm, self.n_iter = n_components, algorithm, n_iter
2854
+ self.n_oversamples = n_oversamples
2855
+ self.power_iteration_normalizer = power_iteration_normalizer
2856
+ self.random_state, self.tol = random_state, tol
2857
+
2858
+ def fit(self, X, y=None):
2859
+ self.fit_transform(X)
2860
+ return self
2861
+
2862
+ def fit_transform(self, X, y=None):
2863
+ if self.algorithm not in ("randomized", "arpack"):
2864
+ raise ValueError(f"algorithm={self.algorithm!r}: expected 'randomized' or 'arpack'")
2865
+ X = fit_x(self, X, ensure_min_features=2)
2866
+ n, p = X.shape
2867
+ c = int(self.n_components)
2868
+ if not 1 <= c <= min(n, p):
2869
+ raise ValueError(f"n_components({c}) must be between 1 and min(n_samples, "
2870
+ f"n_features)={min(n, p)}.")
2871
+ k = _gramops_kernels()
2872
+ V, s, Z = np.zeros((p, c)), np.zeros(c), np.zeros((n, c))
2873
+ if not _issparse(X):
2874
+ (k.tsvd_tall if n >= p else k.tsvd_wide)(X, V, s, Z, n, p, c)
2875
+ full = np.var(X, axis=0).sum()
2876
+ else:
2877
+ if n >= p:
2878
+ k.tsvd_gram(_sparse_gram(X), V, s, p, c)
2879
+ Z = _dot(X, V)
2880
+ else:
2881
+ U = np.zeros((n, c))
2882
+ k.tsvd_gram(_sparse_gram(as_csr(X.T)), U, s, n, c)
2883
+ with np.errstate(divide="ignore", invalid="ignore"):
2884
+ V = np.where(s > 0, _dot(X, U, transpose=True) / s, 0.0)
2885
+ Z = U * s
2886
+ V, Z = np.ascontiguousarray(V), np.ascontiguousarray(Z)
2887
+ k.tsvd_flip(V, Z, n, p, c)
2888
+ m = _sparse_mean(X)
2889
+ full = float(np.sum(np.asarray(X.multiply(X).mean(axis=0)).ravel() - m * m))
2890
+ self.components_ = np.ascontiguousarray(V.T)
2891
+ self.singular_values_ = s
2892
+ self.explained_variance_ = np.var(Z, axis=0)
2893
+ self.explained_variance_ratio_ = self.explained_variance_ / full if full > 0 \
2894
+ else np.zeros(c)
2895
+ return Z
2896
+
2897
+ def transform(self, X):
2898
+ check_is_fitted(self)
2899
+ X = pred_x(self, X)
2900
+ return _dot(X, self.components_.T) if _issparse(X) else X @ self.components_.T
2901
+
2902
+ def inverse_transform(self, X):
2903
+ check_is_fitted(self)
2904
+ return np.asarray(X) @ self.components_
2905
+
2906
+
2907
+ def _convergence_warning():
2908
+ try:
2909
+ from sklearn.exceptions import ConvergenceWarning
2910
+ return ConvergenceWarning
2911
+ except ImportError:
2912
+ return UserWarning
2913
+
2914
+
2915
+ def _covariance(X):
2916
+ """(Xc'Xc / n, column means) from X'X less n m m', the centred copy
2917
+ only when a column's mean dwarfs its spread (_centered_gram's rule)."""
2918
+ n = X.shape[0]
2919
+ xm = X.mean(axis=0)
2920
+ G = _gram(X)
2921
+ nm2 = n * xm * xm
2922
+ if np.all(np.diagonal(G) - nm2 > 1e-4 * nm2):
2923
+ G -= np.outer(xm, n * xm)
2924
+ else:
2925
+ G = _gram(np.ascontiguousarray(X - xm))
2926
+ return G / n, xm
2927
+
2928
+
2929
+ def _ortho_rotation(components, method="varimax", tol=1e-6, max_iter=100):
2930
+ # scikit-learn's decomposition._factor_analysis._ortho_rotation
2931
+ nrow, ncol = components.shape
2932
+ rotation_matrix = np.eye(ncol)
2933
+ var = 0
2934
+ for _ in range(max_iter):
2935
+ comp_rot = components @ rotation_matrix
2936
+ if method == "varimax":
2937
+ tmp = comp_rot * ((comp_rot ** 2).sum(axis=0) / nrow)
2938
+ else:
2939
+ tmp = 0
2940
+ u, s, v = np.linalg.svd(components.T @ (comp_rot ** 3 - tmp))
2941
+ rotation_matrix = u @ v
2942
+ var_new = np.sum(s)
2943
+ if var != 0 and var_new < var * (1 + tol):
2944
+ break
2945
+ var = var_new
2946
+ return (components @ rotation_matrix).T
2947
+
2948
+
2949
+ class GramFactorAnalysis(Tagged, TransformerMixin, BaseEstimator):
2950
+ """scikit-learn's ``FactorAnalysis`` over the covariance
2951
+ (``examples/kernel-only/fa.scm``): scikit-learn takes, every
2952
+ iteration, the SVD of the n x p matrix Xc / (sqrt(psi) sqrt(n));
2953
+ its squared singular values and right singular vectors are the
2954
+ eigenpairs of D^-1 C D^-1 for C = Xc'Xc / n (formed once, by
2955
+ dsyrk) and D = diag(sqrt psi), so each iteration here is the top
2956
+ ``n_components`` eigenpairs of a p x p matrix (dsyevr) and the rows
2957
+ are read once. The eigenproblem is exact: what
2958
+ ``svd_method="lapack"`` computes (to 1e-13 here, iterations alike);
2959
+ the default ``"randomized"`` approximates it, so against that one
2960
+ the fit agrees to its approximation. ``iterated_power`` and
2961
+ ``random_state`` are taken for the interface.
2962
+
2963
+ Attributes after fit: components_, noise_variance_, loglike_,
2964
+ n_iter_, mean_, n_features_in_.
2965
+ """
2966
+
2967
+ def __init__(self, n_components=None, *, tol=1e-2, copy=True, max_iter=1000,
2968
+ noise_variance_init=None, svd_method="randomized", iterated_power=3,
2969
+ rotation=None, random_state=0):
2970
+ self.n_components, self.tol, self.copy, self.max_iter = n_components, tol, copy, max_iter
2971
+ self.noise_variance_init, self.svd_method = noise_variance_init, svd_method
2972
+ self.iterated_power, self.rotation, self.random_state = iterated_power, rotation, random_state
2973
+
2974
+ def fit(self, X, y=None):
2975
+ if self.svd_method not in ("lapack", "randomized"):
2976
+ raise ValueError(f"svd_method={self.svd_method!r}: expected 'lapack' or 'randomized'")
2977
+ if self.rotation not in (None, "varimax", "quartimax"):
2978
+ raise ValueError(f"rotation={self.rotation!r}: expected None, 'varimax' or 'quartimax'")
2979
+ X = fit_x(self, X)
2980
+ n, p = X.shape
2981
+ c = p if self.n_components is None else int(self.n_components)
2982
+ C, self.mean_ = _covariance(X)
2983
+ var = np.diagonal(C).copy()
2984
+ if self.noise_variance_init is None:
2985
+ psi = np.ones(p)
2986
+ else:
2987
+ if len(self.noise_variance_init) != p:
2988
+ raise ValueError("noise_variance_init dimension does not with number of "
2989
+ "features : %d != %d" % (len(self.noise_variance_init), p))
2990
+ psi = np.array(self.noise_variance_init, dtype=np.float64)
2991
+ maxit = int(self.max_iter)
2992
+ W, ll = np.zeros((c, p)), np.zeros(max(maxit, 1))
2993
+ it = _gramops_kernels().fa_fit(np.ascontiguousarray(C), var, psi, W, ll, n, p, c,
2994
+ maxit, float(self.tol))
2995
+ if it > maxit:
2996
+ warnings.warn("FactorAnalysis did not converge. You might want to increase "
2997
+ "the number of iterations.", _convergence_warning())
2998
+ it = maxit
2999
+ self.components_ = W
3000
+ if self.rotation is not None:
3001
+ self.components_ = _ortho_rotation(W.T, method=self.rotation)[:c]
3002
+ self.noise_variance_ = psi
3003
+ self.loglike_ = list(ll[:it])
3004
+ self.n_iter_ = it
3005
+ return self
3006
+
3007
+ def transform(self, X):
3008
+ check_is_fitted(self)
3009
+ X = pred_x(self, X)
3010
+ Wpsi = self.components_ / self.noise_variance_
3011
+ cov_z = np.linalg.inv(np.eye(len(self.components_)) + Wpsi @ self.components_.T)
3012
+ return ((X - self.mean_) @ Wpsi.T) @ cov_z
3013
+
3014
+ def get_covariance(self):
3015
+ check_is_fitted(self)
3016
+ cov = self.components_.T @ self.components_
3017
+ cov.flat[::len(cov) + 1] += self.noise_variance_
3018
+ return cov
3019
+
3020
+ def get_precision(self):
3021
+ check_is_fitted(self)
3022
+ p = self.components_.shape[1]
3023
+ if self.n_components == 0:
3024
+ return np.diag(1.0 / self.noise_variance_)
3025
+ if self.n_components == p:
3026
+ return np.linalg.inv(self.get_covariance())
3027
+ W = self.components_
3028
+ P = (W / self.noise_variance_) @ W.T
3029
+ P.flat[::len(P) + 1] += 1.0
3030
+ P = W.T @ (np.linalg.inv(P) @ W)
3031
+ P /= self.noise_variance_[:, None]
3032
+ P /= -self.noise_variance_[None, :]
3033
+ P.flat[::len(P) + 1] += 1.0 / self.noise_variance_
3034
+ return P
3035
+
3036
+ def score_samples(self, X):
3037
+ check_is_fitted(self)
3038
+ Xr = pred_x(self, X) - self.mean_
3039
+ P = self.get_precision()
3040
+ sign, logdet = np.linalg.slogdet(P)
3041
+ ll = -0.5 * (Xr * (Xr @ P)).sum(axis=1)
3042
+ ll -= 0.5 * (Xr.shape[1] * np.log(2.0 * np.pi) - (logdet if sign > 0 else -np.inf))
3043
+ return ll
3044
+
3045
+ def score(self, X, y=None):
3046
+ return float(np.mean(self.score_samples(X)))
3047
+
3048
+
3049
+ class GramLinearRegression(Tagged, RegressorMixin, BaseEstimator):
3050
+ """scikit-learn's ``LinearRegression`` over the Gram matrix
3051
+ (``examples/kernel-only/linreg.scm``): the rows read once into
3052
+ Xc'Xc and Xc'y (dsyrk, dgemm; csr-gram and csr-mm for a scipy.sparse
3053
+ X), then the normal equations of the column-scaled Gram solved by
3054
+ Cholesky (dposv), where scikit-learn runs LAPACK's gelsd on the
3055
+ n x p design (lsqr on a sparse one). The normal equations square
3056
+ the condition number, so the Gram's answer is taken only when the
3057
+ scaled Gram's condition number (dpocon's estimate) is at most 1e6
3058
+ (relative error about 1e-10) and the design has full rank at
3059
+ ``tol``; otherwise -- and for ``positive=True`` (scipy's nnls, dense
3060
+ X only, as in scikit-learn) -- the fit is scikit-learn's own: least
3061
+ squares on the centred X, or lsqr at ``tol`` on a sparse one.
3062
+ ``rank_`` and ``singular_`` come from the Gram's eigenvalues
3063
+ (dsyevd), computed when first read; the Gram is kept for them.
3064
+ ``sample_weight`` scales the centred rows by its square root, as
3065
+ scikit-learn does.
3066
+
3067
+ Attributes after fit: coef_, intercept_, rank_ and singular_ (not
3068
+ after lsqr), n_features_in_.
3069
+ """
3070
+ _multi_output = True
3071
+
3072
+ def __init__(self, *, fit_intercept=True, copy_X=True, tol=1e-6, n_jobs=None,
3073
+ positive=False):
3074
+ self.fit_intercept, self.copy_X, self.tol = fit_intercept, copy_X, tol
3075
+ self.n_jobs, self.positive = n_jobs, positive
3076
+
3077
+ @property
3078
+ def _sparse(self):
3079
+ return not self.positive
3080
+
3081
+ def fit(self, X, y, sample_weight=None):
3082
+ X, y = fit_xy(self, X, y, multi_output=True)
3083
+ n, p = X.shape
3084
+ sparse = _issparse(X)
3085
+ tol = float(self.tol)
3086
+ t = 1 if y.ndim == 1 else y.shape[1]
3087
+ if sample_weight is not None:
3088
+ sw = np.asarray(sample_weight, dtype=np.float64)
3089
+ sw = np.full(n, float(sw)) if sw.ndim == 0 else sw
3090
+ if sw.shape != (n,):
3091
+ raise ValueError(f"sample_weight.shape == {sw.shape}, expected {(n,)}!")
3092
+ if np.all(sw == 0):
3093
+ raise ValueError("Sample weights must contain at least one non-zero number.")
3094
+ else:
3095
+ sw = None
3096
+ if sw is None and not sparse:
3097
+ G, B, xm, ym = _centered_gram(X, y, self.fit_intercept)
3098
+ r = None
3099
+ else:
3100
+ # rows scaled by sqrt(w): (Xw'Xw - S xm xm') and (Xw'yw - S xm ym')
3101
+ w = np.ones(n) if sw is None else sw
3102
+ S = w.sum()
3103
+ r = np.sqrt(w)
3104
+ ry = r[:, None] if y.ndim > 1 else r
3105
+ if self.fit_intercept:
3106
+ xm = (_dot(X, w, transpose=True) if sparse else w @ X) / S
3107
+ ym = w @ y / S
3108
+ else:
3109
+ xm, ym = np.zeros(p), (np.zeros(t) if y.ndim > 1 else 0.0)
3110
+ if sparse:
3111
+ import scipy.sparse as sp
3112
+ Xw = X if sw is None else as_csr(sp.diags(r) @ X)
3113
+ G = _sparse_gram(Xw) - S * np.outer(xm, xm)
3114
+ B = _dot(Xw, ry * y, transpose=True) - S * np.multiply.outer(xm, ym)
3115
+ else:
3116
+ Xw = np.ascontiguousarray(r[:, None] * (X - xm))
3117
+ G, B = _gram(Xw), _gram_xy(Xw, np.ascontiguousarray(ry * (y - ym)))
3118
+ coef = None
3119
+ for name in ("_rank", "_singular", "_kept"):
3120
+ vars(self).pop(name, None)
3121
+ if not self.positive:
3122
+ cols = np.zeros((p, t))
3123
+ if _gramops_kernels().linreg_solve(np.array(G, dtype=np.float64, order="C"),
3124
+ np.array(B.reshape(p, t), dtype=np.float64,
3125
+ order="C"),
3126
+ cols, p, t, 1e-6, tol) == 1:
3127
+ coef = cols
3128
+ # rank_ and singular_ from G's eigenvalues, on first use
3129
+ self._kept = (np.array(G, dtype=np.float64, order="C"), tol)
3130
+ if coef is None:
3131
+ if r is None:
3132
+ r, ry = np.ones(n), np.ones(n) if y.ndim == 1 else np.ones((n, 1))
3133
+ ys = ry * (y - ym)
3134
+ if sparse:
3135
+ from scipy.sparse.linalg import LinearOperator, lsqr
3136
+ Xw = X if sw is None else as_csr(sp.diags(r) @ X)
3137
+ op = LinearOperator((n, p), matvec=lambda b: Xw @ b - r * (b @ xm),
3138
+ rmatvec=lambda u: Xw.T @ u - xm * (u @ r))
3139
+ Y2 = ys.reshape(n, -1)
3140
+ coef = np.column_stack([lsqr(op, Y2[:, j], atol=tol, btol=tol)[0]
3141
+ for j in range(t)])
3142
+ else:
3143
+ Xs = np.ascontiguousarray(r[:, None] * (X - xm))
3144
+ if self.positive:
3145
+ from scipy import optimize
3146
+ Y2 = ys.reshape(n, -1)
3147
+ coef = np.column_stack([optimize.nnls(Xs, Y2[:, j])[0] for j in range(t)])
3148
+ else:
3149
+ from scipy import linalg
3150
+ coef, _, self._rank, self._singular = linalg.lstsq(Xs, ys.reshape(n, -1),
3151
+ cond=tol)
3152
+ if y.ndim == 1:
3153
+ self.coef_ = coef[:, 0]
3154
+ self.intercept_ = float(ym - xm @ self.coef_) if self.fit_intercept else 0.0
3155
+ else:
3156
+ self.coef_ = np.ascontiguousarray(coef.T)
3157
+ self.intercept_ = ym - xm @ coef if self.fit_intercept else np.zeros(t)
3158
+ return self
3159
+
3160
+ @property
3161
+ def rank_(self):
3162
+ self._spectrum()
3163
+ return self._rank
3164
+
3165
+ @property
3166
+ def singular_(self):
3167
+ self._spectrum()
3168
+ return self._singular
3169
+
3170
+ def _spectrum(self):
3171
+ d = vars(self)
3172
+ if "_rank" in d:
3173
+ return
3174
+ if "_kept" not in d:
3175
+ raise AttributeError("rank_ and singular_ are not set (a sparse X solved by lsqr, "
3176
+ "or not fitted)")
3177
+ G, tol = d["_kept"]
3178
+ sv = np.zeros(G.shape[0])
3179
+ self._rank = _gramops_kernels().linreg_singular(G.copy(), sv, G.shape[0], tol)
3180
+ self._singular = sv
3181
+
3182
+ def predict(self, X):
3183
+ X = pred_x(self, X)
3184
+ return (_dot(X, self.coef_.T) if _issparse(X) else X @ self.coef_.T) + self.intercept_
3185
+
3186
+
3187
+ def _pls_moments(X, Y, scale):
3188
+ """Centred (and, with scale, standardised) Cxx, Cxy, Cyy, with the
3189
+ means and deviations: from X'X, X'Y and Y'Y less the n m m' terms,
3190
+ the centred copies only when a column's mean dwarfs its spread (the
3191
+ correction would cancel its digits)."""
3192
+ n = X.shape[0]
3193
+ xm, ym = X.mean(axis=0), Y.mean(axis=0)
3194
+ Gxx, Gxy, Gyy = _gram(X), _gram_xy(X, Y), _gram(np.ascontiguousarray(Y))
3195
+ Gxy = Gxy.reshape(X.shape[1], Y.shape[1])
3196
+ nx, ny = n * xm * xm, n * ym * ym
3197
+ if np.all(np.diagonal(Gxx) - nx > 1e-4 * nx) and np.all(np.diagonal(Gyy) - ny > 1e-4 * ny):
3198
+ Cxx = Gxx - np.outer(xm, n * xm)
3199
+ Cxy = Gxy - np.outer(xm, n * ym)
3200
+ Cyy = Gyy - np.outer(ym, n * ym)
3201
+ else:
3202
+ Xc, Yc = np.ascontiguousarray(X - xm), np.ascontiguousarray(Y - ym)
3203
+ Cxx, Cyy = _gram(Xc), _gram(Yc)
3204
+ Cxy = _gram_xy(Xc, Yc).reshape(X.shape[1], Y.shape[1])
3205
+ if scale:
3206
+ xs = np.sqrt(np.maximum(np.diagonal(Cxx), 0.0) / (n - 1))
3207
+ ys = np.sqrt(np.maximum(np.diagonal(Cyy), 0.0) / (n - 1))
3208
+ xs[xs == 0.0] = 1.0
3209
+ ys[ys == 0.0] = 1.0
3210
+ Cxx = Cxx / np.outer(xs, xs)
3211
+ Cxy = Cxy / np.outer(xs, ys)
3212
+ Cyy = Cyy / np.outer(ys, ys)
3213
+ else:
3214
+ xs, ys = np.ones(X.shape[1]), np.ones(Y.shape[1])
3215
+ return (np.ascontiguousarray(Cxx), np.ascontiguousarray(Cxy), np.ascontiguousarray(Cyy),
3216
+ xm, ym, xs, ys)
3217
+
3218
+
3219
+ class _GramPLS(Tagged, TransformerMixin, BaseEstimator):
3220
+ # scikit-learn's _PLS over the cross products (examples/kernel-only/pls.scm)
3221
+ _multi_output = True
3222
+ _mode, _canon = 0, 0
3223
+
3224
+ def fit(self, X, y):
3225
+ X, y = fit_xy(self, X, y, multi_output=True)
3226
+ n, p = X.shape
3227
+ if n < 2:
3228
+ raise ValueError(f"Found array with {n} sample(s) (shape={X.shape}) while a "
3229
+ "minimum of 2 is required.")
3230
+ self._predict_1d = y.ndim == 1
3231
+ Y = y.reshape(n, -1)
3232
+ q = Y.shape[1]
3233
+ k = int(self.n_components)
3234
+ upper = min(n, p) if not self._canon else min(n, p, q)
3235
+ if not 1 <= k <= upper:
3236
+ raise ValueError(f"`n_components` upper bound is {upper}. Got {k} instead. "
3237
+ "Reduce `n_components`.")
3238
+ algo = 1 if getattr(self, "algorithm", "nipals") == "svd" else 0
3239
+ Cxx, Cxy, Cyy, self._x_mean, self._y_mean, self._x_std, self._y_std = \
3240
+ _pls_moments(X, Y, self.scale)
3241
+ xw, yw = np.zeros((p, k)), np.zeros((q, k))
3242
+ xl, yl = np.zeros((p, k)), np.zeros((q, k))
3243
+ niter = np.zeros(k, dtype=np.int32)
3244
+ found = _gramops_kernels().pls_fit(Cxx, Cxy, Cyy, xw, yw, xl, yl, niter, p, q, k,
3245
+ self._mode, self._canon, algo,
3246
+ int(self.max_iter), float(self.tol))
3247
+ if found < k:
3248
+ warnings.warn(f"y residual is constant at iteration {found}")
3249
+ # scikit-learn keeps the list empty for the svd algorithm
3250
+ self.n_iter_ = [int(t) for t in niter[:found]] if algo == 0 else []
3251
+ if algo == 0:
3252
+ if any(t == int(self.max_iter) for t in self.n_iter_):
3253
+ warnings.warn("Maximum number of iterations reached", UserWarning)
3254
+ self.x_weights_, self.y_weights_ = xw, yw
3255
+ self.x_loadings_, self.y_loadings_ = xl, yl
3256
+ self.x_rotations_ = xw @ np.linalg.pinv(xl.T @ xw)
3257
+ self.y_rotations_ = yw @ np.linalg.pinv(yl.T @ yw)
3258
+ coef = self.x_rotations_ @ yl.T
3259
+ self.coef_ = (coef * self._y_std).T / self._x_std
3260
+ self.intercept_ = self._y_mean
3261
+ self._n_features_out = k
3262
+ self._X, self._Y = X, Y
3263
+ return self
3264
+
3265
+ def transform(self, X, y=None, copy=True):
3266
+ check_is_fitted(self)
3267
+ Xs = (pred_x(self, X) - self._x_mean) / self._x_std
3268
+ xs = Xs @ self.x_rotations_
3269
+ if y is None:
3270
+ return xs
3271
+ Y = np.asarray(y, dtype=np.float64)
3272
+ Y = Y.reshape(-1, 1) if Y.ndim == 1 else Y
3273
+ return xs, ((Y - self._y_mean) / self._y_std) @ self.y_rotations_
3274
+
3275
+ def fit_transform(self, X, y=None):
3276
+ return self.fit(X, y).transform(X, y)
3277
+
3278
+ def inverse_transform(self, X, y=None):
3279
+ check_is_fitted(self)
3280
+ Xr = np.asarray(X, dtype=np.float64) @ self.x_loadings_.T * self._x_std + self._x_mean
3281
+ if y is None:
3282
+ return Xr
3283
+ Yr = np.asarray(y, dtype=np.float64) @ self.y_loadings_.T * self._y_std + self._y_mean
3284
+ return Xr, Yr
3285
+
3286
+ def predict(self, X, copy=True):
3287
+ check_is_fitted(self)
3288
+ yp = (pred_x(self, X) - self._x_mean) @ self.coef_.T + self.intercept_
3289
+ return yp.ravel() if self._predict_1d else yp
3290
+
3291
+
3292
+ class GramPLSRegression(RegressorMixin, _GramPLS):
3293
+ """scikit-learn's ``PLSRegression`` over the cross products
3294
+ (``examples/kernel-only/pls.scm``): X'X (dsyrk), X'Y and Y'Y once,
3295
+ then NIPALS and the regression deflation as products and rank-one
3296
+ updates of those p x p, p x q and q x q matrices, never the n rows
3297
+ again. The scores x_scores_ = X R and y_scores_ (Y less the earlier
3298
+ components' X scores, times the Y weights) are formed at the end.
3299
+
3300
+ Attributes after fit: x_weights_, y_weights_, x_loadings_,
3301
+ y_loadings_, x_rotations_, y_rotations_, x_scores_, y_scores_,
3302
+ coef_, intercept_, n_iter_, n_features_in_.
3303
+ """
3304
+ _mode, _canon = 0, 0
3305
+
3306
+ def __init__(self, n_components=2, *, scale=True, max_iter=500, tol=1e-06, copy=True):
3307
+ self.n_components, self.scale, self.max_iter = n_components, scale, max_iter
3308
+ self.tol, self.copy = tol, copy
3309
+
3310
+ def fit(self, X, y):
3311
+ super().fit(X, y)
3312
+ Xs = (self._X - self._x_mean) / self._x_std
3313
+ Ys = (self._Y - self._y_mean) / self._y_std
3314
+ T = Xs @ self.x_rotations_
3315
+ U = Ys @ self.y_weights_
3316
+ for k in range(U.shape[1]):
3317
+ # Y deflated by the earlier components' X scores (regression mode)
3318
+ U[:, k] -= T[:, :k] @ (self.y_loadings_[:, :k].T @ self.y_weights_[:, k])
3319
+ U[:, k] /= self.y_weights_[:, k] @ self.y_weights_[:, k]
3320
+ self.x_scores_, self.y_scores_ = T, U
3321
+ del self._X, self._Y
3322
+ return self
3323
+
3324
+ def fit_transform(self, X, y=None):
3325
+ return self.fit(X, y).transform(X, y)
3326
+
3327
+
3328
+ class GramPLSCanonical(_GramPLS):
3329
+ """scikit-learn's ``PLSCanonical`` (canonical deflation, mode A,
3330
+ ``algorithm`` "nipals" or "svd") over the cross products, as
3331
+ ``GramPLSRegression``."""
3332
+ _mode, _canon = 0, 1
3333
+
3334
+ def __init__(self, n_components=2, *, scale=True, algorithm="nipals", max_iter=500,
3335
+ tol=1e-06, copy=True):
3336
+ self.n_components, self.scale, self.algorithm = n_components, scale, algorithm
3337
+ self.max_iter, self.tol, self.copy = max_iter, tol, copy
3338
+
3339
+ def fit(self, X, y):
3340
+ if self.algorithm not in ("nipals", "svd"):
3341
+ raise ValueError(f"algorithm={self.algorithm!r}: expected 'nipals' or 'svd'")
3342
+ super().fit(X, y)
3343
+ del self._X, self._Y
3344
+ return self
3345
+
3346
+
3347
+ class GramCCA(_GramPLS):
3348
+ """scikit-learn's ``CCA`` (canonical deflation, mode B: pinv of each
3349
+ block from the eigenproblem of its Gram, cut where _pinv2_old cuts)
3350
+ over the cross products, as ``GramPLSRegression``."""
3351
+ _mode, _canon = 1, 1
3352
+
3353
+ def __init__(self, n_components=2, *, scale=True, max_iter=500, tol=1e-06, copy=True):
3354
+ self.n_components, self.scale, self.max_iter = n_components, scale, max_iter
3355
+ self.tol, self.copy = tol, copy
3356
+
3357
+ def fit(self, X, y):
3358
+ super().fit(X, y)
3359
+ del self._X, self._Y
3360
+ return self
3361
+
3362
+
3363
+ class GramPLSSVD(Tagged, TransformerMixin, BaseEstimator):
3364
+ """scikit-learn's ``PLSSVD``: the SVD of the centred (scaled) X'Y,
3365
+ formed from X'Y less n mx my' instead of from centred copies."""
3366
+ _multi_output = True
3367
+
3368
+ def __init__(self, n_components=2, *, scale=True, copy=True):
3369
+ self.n_components, self.scale, self.copy = n_components, scale, copy
3370
+
3371
+ def fit(self, X, y):
3372
+ X, y = fit_xy(self, X, y, multi_output=True)
3373
+ n, p = X.shape
3374
+ if n < 2:
3375
+ raise ValueError(f"Found array with {n} sample(s) (shape={X.shape}) while a "
3376
+ "minimum of 2 is required.")
3377
+ Y = y.reshape(n, -1)
3378
+ k = int(self.n_components)
3379
+ upper = min(n, p, Y.shape[1])
3380
+ if not 1 <= k <= upper:
3381
+ raise ValueError(f"`n_components` upper bound is {upper}. Got {k} instead. "
3382
+ "Reduce `n_components`.")
3383
+ _, C, _, self._x_mean, self._y_mean, self._x_std, self._y_std = \
3384
+ _pls_moments(X, Y, self.scale)
3385
+ U, _, Vt = np.linalg.svd(C, full_matrices=False)
3386
+ U, Vt = U[:, :k], Vt[:k]
3387
+ # svd_flip, u-based: each column of U's largest entry positive
3388
+ sg = np.sign(U[np.argmax(np.abs(U), axis=0), np.arange(k)])
3389
+ sg[sg == 0] = 1.0
3390
+ self.x_weights_, self.y_weights_ = U * sg, (Vt * sg[:, None]).T
3391
+ self._n_features_out = k
3392
+ return self
3393
+
3394
+ def transform(self, X, y=None):
3395
+ check_is_fitted(self)
3396
+ xs = ((pred_x(self, X) - self._x_mean) / self._x_std) @ self.x_weights_
3397
+ if y is None:
3398
+ return xs
3399
+ Y = np.asarray(y, dtype=np.float64)
3400
+ Y = Y.reshape(-1, 1) if Y.ndim == 1 else Y
3401
+ return xs, ((Y - self._y_mean) / self._y_std) @ self.y_weights_
3402
+
3403
+ def fit_transform(self, X, y=None):
3404
+ return self.fit(X, y).transform(X, y)
3405
+
3406
+
3407
+ class ParallelFastICA(Tagged, TransformerMixin, BaseEstimator):
3408
+ """FastICA, scikit-learn's ``FastICA`` at its defaults translated
3409
+ whole (``examples/kernel-only/fastica.scm``: algorithm="parallel",
3410
+ fun="logcosh", whiten="unit-variance", whiten_solver="svd" -- the
3411
+ singular vectors of X' taken from the eigenvectors of X'X, signed as
3412
+ scikit-learn signs them). The start is ``RandomState(random_state)
3413
+ .normal(size=(k, k))``, scikit-learn's draw, unless ``w_init`` is
3414
+ given; with the same start the fit is scikit-learn's to rounding.
3415
+
3416
+ Attributes after fit: components_, mixing_, mean_, whitening_, n_iter_.
3417
+ """
3418
+
3419
+ def __init__(self, n_components=None, *, max_iter=200, tol=1e-4, w_init=None,
3420
+ random_state=None):
3421
+ self.n_components, self.max_iter, self.tol = n_components, max_iter, tol
3422
+ self.w_init, self.random_state = w_init, random_state
3423
+
3424
+ def fit(self, X, y=None):
3425
+ X = fit_x(self, X, ensure_min_samples=2)
3426
+ n, p = X.shape
3427
+ k = min(n, p) if self.n_components is None else min(int(self.n_components), n, p)
3428
+ if self.w_init is None:
3429
+ w0 = np.random.RandomState(self.random_state).normal(size=(k, k))
3430
+ else:
3431
+ w0 = np.asarray(self.w_init, dtype=np.float64)
3432
+ w0 = np.ascontiguousarray(w0)
3433
+ self.components_ = np.zeros((k, p)); self.whitening_ = np.zeros((k, p))
3434
+ self._unmixing = np.zeros((k, k)); self.mean_ = np.zeros(p)
3435
+ self.n_iter_ = _gpu_or_cpu(n * p, getattr(self, "backend", None)).fastica(
3436
+ X, w0, self.components_, self.whitening_, self._unmixing, self.mean_,
3437
+ int(self.max_iter), float(self.tol), n, p, k)
3438
+ self.mixing_ = np.linalg.pinv(self.components_)
3439
+ return self
3440
+
3441
+ def transform(self, X):
3442
+ return (pred_x(self, X) - self.mean_) @ self.components_.T
3443
+
3444
+ def fit_transform(self, X, y=None):
3445
+ return self.fit(X).transform(X)
3446
+
3447
+
3448
+ class CovARDRegression(Tagged, RegressorMixin, BaseEstimator):
3449
+ """Automatic relevance determination, scikit-learn's ``ARDRegression``
3450
+ for n >= p translated whole (``examples/kernel-only/ard.scm``): each
3451
+ iteration sigma = pinvh(diag(lambda) + alpha G) over the kept
3452
+ features (the eigenproblem in the subset, scipy's cutoff), then
3453
+ coef, gamma, lambda, alpha and the pruning at ``threshold_lambda``,
3454
+ stopping on the coefficients' summed change. ``hoist=True`` (the
3455
+ default) takes the kept features' Gram from X'X formed once;
3456
+ ``hoist=False`` forms it from X every iteration, as scikit-learn
3457
+ does. Same iterations and coefficients to rounding either way.
3458
+
3459
+ Attributes after fit: coef_, intercept_, alpha_, lambda_, sigma_,
3460
+ n_iter_.
3461
+ """
3462
+
3463
+ def __init__(self, *, max_iter=300, tol=1e-3, alpha_1=1e-6, alpha_2=1e-6,
3464
+ lambda_1=1e-6, lambda_2=1e-6, threshold_lambda=1e4, fit_intercept=True,
3465
+ hoist=True):
3466
+ self.max_iter, self.tol = max_iter, tol
3467
+ self.alpha_1, self.alpha_2, self.lambda_1, self.lambda_2 = alpha_1, alpha_2, lambda_1, lambda_2
3468
+ self.threshold_lambda, self.fit_intercept, self.hoist = threshold_lambda, fit_intercept, hoist
3469
+
3470
+ def fit(self, X, y):
3471
+ X, y = fit_xy(self, X, y)
3472
+ Xc, yc, xm, ym = _center(X, y, self.fit_intercept)
3473
+ n, p = Xc.shape
3474
+ if n < p:
3475
+ raise ValueError(f"CovARDRegression is the n >= p route (_update_sigma); got "
3476
+ f"n_samples = {n} for {p} features")
3477
+ self.coef_ = np.zeros(p)
3478
+ self.lambda_ = np.zeros(p)
3479
+ sigma = np.zeros(p * p)
3480
+ out = np.zeros(2)
3481
+ self.n_iter_ = _gramops_kernels().ard(
3482
+ Xc, np.ascontiguousarray(yc), self.coef_, sigma, self.lambda_, out,
3483
+ int(self.max_iter), float(self.tol), float(self.alpha_1), float(self.alpha_2),
3484
+ float(self.lambda_1), float(self.lambda_2), float(self.threshold_lambda),
3485
+ 1 if self.hoist else 0, n, p)
3486
+ k = int(out[1])
3487
+ self.alpha_ = float(out[0])
3488
+ self.sigma_ = sigma[:k * k].reshape(k, k).copy()
3489
+ self.intercept_ = ym - float(xm @ self.coef_)
3490
+ return self
3491
+
3492
+ def predict(self, X):
3493
+ return pred_x(self, X) @ self.coef_ + self.intercept_
3494
+
3495
+
3496
+ def _gpu_or_cpu(size, backend=None):
3497
+ """The --cuda translation (kernels and device-resident cuBLAS) when it
3498
+ was built, a device answers, the backend allows it and the problem has
3499
+ at least a million entries; the CPU library otherwise."""
3500
+ import os
3501
+ from ._libfind import gpu_built
3502
+ if (backend in (None, "cuda") and size >= 1e6 and not os.environ.get("SCM2CPP_NO_DEVICE")
3503
+ and gpu_built() and cuda_available()):
3504
+ import importlib
3505
+ return importlib.import_module(f"{__name__}._generated._loader_gpu_cuda")
3506
+ return _gramops_kernels()
3507
+
3508
+
3509
+ def _accel(work):
3510
+ """The --cublas build of the selection and Gram products, when it was
3511
+ built, a device answers, and WORK (flops) is large enough to pay for
3512
+ the transfer; else None."""
3513
+ import os
3514
+ from ._libfind import accel_built
3515
+ if (work < 2e9 or os.environ.get("SCM2CPP_NO_DEVICE") or not accel_built()
3516
+ or not cuda_available()):
3517
+ return None
3518
+ import importlib
3519
+ return importlib.import_module(f"{__name__}._generated._loader_accel_cublas")
3520
+
3521
+
3522
+ # Products under this many multiply-adds go to numpy: no BLAS threads
3523
+ # them, and a ctypes call to the package's library costs 10 us more than
3524
+ # numpy's (a 200 x 10 GramRidge took twice as long through it)
3525
+ _SMALL = 1e6
3526
+
3527
+
3528
+ def _gram(Xc, backend=None):
3529
+ """X'X: gram.scm's gram-xx where the BLAS build is here (one dsyrk on
3530
+ every core, half the flops of numpy's X.T @ X, which is a dgemm), on
3531
+ the device for a large product when one answers, else numpy. With
3532
+ the BLAS build the device is taken by default only from p = 4000:
3533
+ the product reads X once, so its copy to the device is most of the
3534
+ device's time, and twenty cores' dsyrk was faster up to p = 2000
3535
+ (200,000 x 200: 0.044 s against 0.096 s)."""
3536
+ from ._libfind import gramops_backend
3537
+ n, p = Xc.shape
3538
+ if backend is None and float(n) * p * p < _SMALL:
3539
+ return np.ascontiguousarray(Xc.T @ Xc)
3540
+ blas = gramops_backend() == "blas"
3541
+ dev = backend == "cublas" or (backend is None and (not blas or p >= 4000))
3542
+ lib = _accel(float(n) * p * p) if dev else None
3543
+ if lib is None:
3544
+ if not blas:
3545
+ return np.ascontiguousarray(Xc.T @ Xc)
3546
+ lib = _gramops_kernels()
3547
+ G = np.zeros((p, p))
3548
+ lib.gram_xx(np.ascontiguousarray(Xc), G, n, p)
3549
+ return G
3550
+
3551
+
3552
+ def _gram_xy(Xc, y):
3553
+ """X'y (y one target or several) by gram.scm's gram-xy where the BLAS
3554
+ build is here, so that the Gram-route fits run on one BLAS: numpy's
3555
+ OpenBLAS keeps its threads spinning after a call, and the next dsyrk
3556
+ of the other library then shared the cores with them (CovRidge at
3557
+ 200,000 x 200 took 0.14 s for a 0.044 s product)."""
3558
+ from ._libfind import gramops_backend
3559
+ n, p = Xc.shape
3560
+ q = 1 if y.ndim == 1 else y.shape[1]
3561
+ if gramops_backend() != "blas" or float(n) * p * q < _SMALL:
3562
+ return Xc.T @ y
3563
+ c = np.zeros((p, q))
3564
+ _gramops_kernels().gram_xy(np.ascontiguousarray(Xc), np.ascontiguousarray(y), c, n, p, q)
3565
+ return c.ravel() if y.ndim == 1 else c
3566
+
3567
+
3568
+ def _ridge_solve(G, c, alpha):
3569
+ """(G + alpha I) b = c by gram.scm's gram-ridge-solve (LAPACK's dposv in the
3570
+ BLAS build), c one column or several; None when the factor breaks
3571
+ down (alpha 0 on a singular G), for the caller's least squares. In
3572
+ the package's library rather than numpy's for the reason _gram_xy
3573
+ gives: numpy's solve between two dsyrk calls cost the next one half
3574
+ its speed. (Until 0.17 this was rfe.scm's Cholesky in loops, 3.7x
3575
+ numpy's solve at p = 200.)"""
3576
+ p = G.shape[0]
3577
+ cols = np.array(c.reshape(p, -1), dtype=np.float64, order="C")
3578
+ if _gramops_kernels().gram_ridge_solve(np.ascontiguousarray(G, dtype=np.float64), cols,
3579
+ float(alpha), p, cols.shape[1]) != 0:
3580
+ return None
3581
+ return cols.ravel() if c.ndim == 1 else cols
3582
+
3583
+
3584
+ def _threads():
3585
+ # the threads the sparse Gram splits into: OMP_NUM_THREADS, else every core
3586
+ try:
3587
+ t = int(os.environ.get("OMP_NUM_THREADS", ""))
3588
+ if t > 0:
3589
+ return t
3590
+ except ValueError:
3591
+ pass
3592
+ return os.cpu_count() or 1
3593
+
3594
+
3595
+ def _sparse_gram(X):
3596
+ """X'X (p x p) for a CSR X by sparse.scm's csr-gram: the rows in
3597
+ order, each row's outer product into the upper triangle. Blocks of
3598
+ rows of equal work (sum nnz_i^2) run on threads (ctypes lets go of
3599
+ the GIL), each into its own G -- as many as fit in about 1 GB -- and
3600
+ the G's are summed, then the triangle mirrored. (Walking the
3601
+ columns instead, each into its own row of one G, visited every row
3602
+ once per entry from anywhere in memory: 12x slower on one core at
3603
+ 200,000 x 200, 5% dense, where this takes 0.025 s and scipy's
3604
+ X.T @ X 0.26 s.)"""
3605
+ from concurrent.futures import ThreadPoolExecutor
3606
+ n, p = X.shape
3607
+ G = np.zeros((p, p))
3608
+ if p == 0 or X.nnz == 0:
3609
+ return G
3610
+ rp, ci, v = X.indptr, X.indices, X.data
3611
+ k = _gramops_kernels()
3612
+ w = np.diff(rp).astype(np.float64) ** 2
3613
+ t = max(1, min(_threads(), n, int(1e9 // (8.0 * p * p)), int(w.sum() // 1e6) + 1))
3614
+ cuts = [0] + list(np.searchsorted(np.cumsum(w), w.sum() * np.arange(1, t) / t) + 1) + [n]
3615
+ blocks = sorted({(int(a), int(b)) for a, b in zip(cuts[:-1], cuts[1:]) if b > a})
3616
+ Gs = [G] + [np.zeros((p, p)) for _ in blocks[1:]]
3617
+ run = lambda j: k.csr_gram(rp, ci, v, Gs[j], p, blocks[j][0], blocks[j][1])
3618
+ if len(blocks) == 1:
3619
+ run(0)
3620
+ else:
3621
+ with ThreadPoolExecutor(len(blocks)) as ex:
3622
+ list(ex.map(run, range(len(blocks))))
3623
+ for H in Gs[1:]:
3624
+ G += H
3625
+ low = np.tril_indices(p, -1)
3626
+ G[low] = G.T[low]
3627
+ return G
3628
+
3629
+
3630
+ def _dot(X, B, transpose=False):
3631
+ """X B (or X'B) for a CSR X and a dense B (1-D or 2-D) by sparse.scm's
3632
+ csr-mm, rows in parallel; scipy's product below a small size."""
3633
+ m = X.shape[1] if transpose else X.shape[0]
3634
+ B2 = np.ascontiguousarray(np.asarray(B, dtype=np.float64).reshape(X.shape[0 if transpose else 1], -1))
3635
+ if float(X.nnz) * B2.shape[1] < _SMALL:
3636
+ out = np.asarray((X.T if transpose else X) @ B2)
3637
+ else:
3638
+ A = X.tocsc() if transpose else X
3639
+ out = np.zeros((m, B2.shape[1]))
3640
+ _gramops_kernels().csr_mm(np.ascontiguousarray(A.indptr, dtype=np.int64),
3641
+ np.ascontiguousarray(A.indices, dtype=np.int32),
3642
+ np.ascontiguousarray(A.data, dtype=np.float64),
3643
+ B2, out, m, B2.shape[1])
3644
+ return out.ravel() if np.ndim(B) == 1 else out
3645
+
3646
+
3647
+ def _sparse_mean(X):
3648
+ return np.asarray(X.mean(axis=0)).ravel()
3649
+
3650
+
3651
+ def _cpu_select_lib():
3652
+ return _gramops_kernels()
3653
+
3654
+
3655
+ def f_regression(X, y, *, center=True, backend=None):
3656
+ """scikit-learn's ``f_regression`` translated (``fscore.scm``): F and
3657
+ p-values of each feature against y. ``y`` may also be n x q, the q
3658
+ targets in one call (one product X'Y, on the device when one answers
3659
+ and the product is large) -- what a loop of scikit-learn's calls
3660
+ gives, column by column. Infinite F (perfect correlation) becomes
3661
+ the largest double and NaN F zero with p-value 1, as
3662
+ force_finite=True has it. p-values need scipy (else None)."""
3663
+ X = np.ascontiguousarray(X, dtype=np.float64)
3664
+ Y = np.asarray(y, dtype=np.float64)
3665
+ one = Y.ndim == 1
3666
+ Y = np.ascontiguousarray(Y.reshape(len(Y), -1))
3667
+ n, p = X.shape
3668
+ q = Y.shape[1]
3669
+ lib = _accel(float(n) * p * q) if backend in (None, "cublas") else None
3670
+ if lib is None:
3671
+ lib = _cpu_select_lib()
3672
+ r = np.zeros((p, q))
3673
+ F = np.zeros((p, q))
3674
+ with np.errstate(divide="ignore", invalid="ignore"):
3675
+ lib.f_regression(X, Y, r, F, 1 if center else 0, n, p, q)
3676
+ dof = n - (2 if center else 1)
3677
+ try:
3678
+ from scipy import stats
3679
+ pv = stats.f.sf(F, 1, dof)
3680
+ except ImportError:
3681
+ pv = None
3682
+ inf = np.isinf(F)
3683
+ F[inf] = np.finfo(np.float64).max
3684
+ nan = np.isnan(F)
3685
+ F[nan] = 0.0
3686
+ if pv is not None:
3687
+ pv[nan] = 1.0
3688
+ if one:
3689
+ return F[:, 0], (None if pv is None else pv[:, 0])
3690
+ return F, pv
3691
+
3692
+
3693
+ def f_classif(X, y):
3694
+ """scikit-learn's ``f_classif`` translated (``fscore.scm``: f_oneway's
3695
+ sums of squares, the class sums one product). p-values need scipy."""
3696
+ X = np.ascontiguousarray(X, dtype=np.float64)
3697
+ classes, lab = np.unique(np.asarray(y), return_inverse=True)
3698
+ n, p = X.shape
3699
+ k = len(classes)
3700
+ F = np.zeros(p)
3701
+ with np.errstate(divide="ignore", invalid="ignore"):
3702
+ _cpu_select_lib().f_classif(X, lab.astype(np.int32), F, n, p, k)
3703
+ try:
3704
+ from scipy import special
3705
+ pv = special.fdtrc(k - 1, n - k, F)
3706
+ except ImportError:
3707
+ pv = None
3708
+ return F, pv
3709
+
3710
+
3711
+ def _clean_nans(scores):
3712
+ scores = np.array(scores, dtype=np.float64, copy=True)
3713
+ scores[np.isnan(scores)] = np.finfo(np.float64).min
3714
+ return scores
3715
+
3716
+
3717
+ class _SelectBase(Tagged, TransformerMixin, BaseEstimator):
3718
+ def fit(self, X, y):
3719
+ X, y = fit_xy(self, X, y, y_numeric=False)
3720
+ sf = self.score_func
3721
+ fn = {"f_classif": f_classif, "f_regression": f_regression}.get(sf, sf)
3722
+ self.scores_, self.pvalues_ = fn(X, y)
3723
+ return self
3724
+
3725
+ def transform(self, X):
3726
+ X = pred_x(self, X)
3727
+ return X[:, self.get_support()]
3728
+
3729
+ def fit_transform(self, X, y):
3730
+ return self.fit(X, y).transform(X)
3731
+
3732
+
3733
+ class SelectKBest(_SelectBase):
3734
+ """scikit-learn's ``SelectKBest`` over the translated F statistics
3735
+ (``score_func`` "f_classif", "f_regression", or one of this module's
3736
+ functions): the k best scores by a stable sort, NaN scores last.
3737
+
3738
+ Attributes after fit: scores_, pvalues_.
3739
+ """
3740
+
3741
+ def __init__(self, score_func="f_classif", *, k=10):
3742
+ self.score_func, self.k = score_func, k
3743
+
3744
+ def get_support(self):
3745
+ check_is_fitted(self)
3746
+ if self.k == "all":
3747
+ return np.ones(len(self.scores_), dtype=bool)
3748
+ mask = np.zeros(len(self.scores_), dtype=bool)
3749
+ if self.k == 0:
3750
+ return mask
3751
+ mask[np.argsort(_clean_nans(self.scores_), kind="mergesort")[-self.k:]] = True
3752
+ return mask
3753
+
3754
+
3755
+ class SelectPercentile(_SelectBase):
3756
+ """scikit-learn's ``SelectPercentile`` over the translated F
3757
+ statistics: scores above the (100 - percentile)th percentile, ties
3758
+ at it kept in order up to the percentile's count.
3759
+
3760
+ Attributes after fit: scores_, pvalues_.
3761
+ """
3762
+
3763
+ def __init__(self, score_func="f_classif", *, percentile=10):
3764
+ self.score_func, self.percentile = score_func, percentile
3765
+
3766
+ def get_support(self):
3767
+ check_is_fitted(self)
3768
+ if self.percentile == 100:
3769
+ return np.ones(len(self.scores_), dtype=bool)
3770
+ if self.percentile == 0:
3771
+ return np.zeros(len(self.scores_), dtype=bool)
3772
+ scores = _clean_nans(self.scores_)
3773
+ threshold = np.percentile(scores, 100 - self.percentile)
3774
+ mask = scores > threshold
3775
+ ties = np.where(scores == threshold)[0]
3776
+ if len(ties):
3777
+ max_feats = int(len(scores) * self.percentile / 100)
3778
+ mask[ties[: max_feats - mask.sum()]] = True
3779
+ return mask
3780
+
3781
+
3782
+ class GramRFE(Tagged, RegressorMixin, TransformerMixin, BaseEstimator):
3783
+ """scikit-learn's ``RFE`` around ``Ridge(alpha)`` (``alpha=0``:
3784
+ ``LinearRegression()``) translated whole (``rfe.scm``): the centred
3785
+ Gram formed once (on the device for a large one when one answers),
3786
+ each round's fit from its Cholesky factor with the dropped features
3787
+ taken out by plane rotations, the features ranked by coef^2 in a
3788
+ stable order. scikit-learn refits from X every round; the ranking
3789
+ and the final coefficients are the same to rounding.
3790
+
3791
+ Attributes after fit: support_, ranking_, n_features_, coef_,
3792
+ intercept_.
3793
+ """
3794
+
3795
+ def __init__(self, alpha=1.0, *, n_features_to_select=None, step=1, backend=None):
3796
+ self.alpha, self.n_features_to_select, self.step = alpha, n_features_to_select, step
3797
+ self.backend = backend
3798
+
3799
+ def fit(self, X, y):
3800
+ X, y = fit_xy(self, X, y)
3801
+ n, p = X.shape
3802
+ k = self.n_features_to_select
3803
+ nsel = p // 2 if k is None else (int(k) if isinstance(k, (int, np.integer)) else int(p * k))
3804
+ step = int(max(1, self.step * p)) if 0.0 < self.step < 1.0 else int(self.step)
3805
+ lib = _accel(float(n) * p * p) if self.backend in (None, "cublas") else None
3806
+ if lib is None:
3807
+ lib = _cpu_select_lib()
3808
+ coef = np.zeros(p)
3809
+ support = np.zeros(p, dtype=np.int32)
3810
+ ranking = np.zeros(p, dtype=np.int32)
3811
+ lib.rfe(X, y, coef, support, ranking, float(self.alpha), nsel, step, n, p)
3812
+ self.support_ = support.astype(bool)
3813
+ self.ranking_ = ranking.astype(int)
3814
+ self.n_features_ = int(self.support_.sum())
3815
+ self.coef_ = coef[self.support_].copy()
3816
+ self.intercept_ = float(y.mean() - X.mean(axis=0)[self.support_] @ self.coef_)
3817
+ return self
3818
+
3819
+ def transform(self, X):
3820
+ return pred_x(self, X)[:, self.support_]
3821
+
3822
+ def predict(self, X):
3823
+ return self.transform(X) @ self.coef_ + self.intercept_
3824
+
3825
+ def fit_transform(self, X, y):
3826
+ return self.fit(X, y).transform(X)
3827
+
3828
+
3829
+ class _GramLarsBase(Tagged, RegressorMixin, BaseEstimator):
3830
+ def _fit_lars(self, X, y, method, alpha, max_iter):
3831
+ X, y = fit_xy(self, X, y)
3832
+ Xc, yc, xm, ym = _center(X, y, self.fit_intercept)
3833
+ n, p = Xc.shape
3834
+ G = _gram(Xc)
3835
+ cov = Xc.T @ yc
3836
+ self.coef_ = np.zeros(p)
3837
+ self.n_iter_ = _classifier_kernels().lars(
3838
+ G, cov, self.coef_, np.zeros(1), np.zeros(1), 0, float(n), float(alpha), method,
3839
+ int(max_iter), float(np.finfo(np.float64).eps), p)
3840
+ self.intercept_ = ym - float(xm @ self.coef_)
3841
+ return self
3842
+
3843
+ def predict(self, X):
3844
+ return pred_x(self, X) @ self.coef_ + self.intercept_
3845
+
3846
+
3847
+ class GramLars(_GramLarsBase):
3848
+ """Least angle regression, scikit-learn's _lars_path_solver with a
3849
+ Gram translated (``examples/kernel-only/lars.scm``, method "lar").
3850
+ ``Lars`` takes the Gram route for n > p (precompute="auto"); here it
3851
+ is taken always, the Gram X'X formed in numpy. ``n_nonzero_coefs``
3852
+ defaults to 500, as there.
3853
+
3854
+ Attributes after fit: coef_, intercept_, n_iter_.
3855
+ """
3856
+
3857
+ def __init__(self, *, n_nonzero_coefs=500, fit_intercept=True):
3858
+ self.n_nonzero_coefs, self.fit_intercept = n_nonzero_coefs, fit_intercept
3859
+
3860
+ def fit(self, X, y):
3861
+ return self._fit_lars(X, y, 0, 0.0, int(self.n_nonzero_coefs))
3862
+
3863
+
3864
+ class GramLassoLars(_GramLarsBase):
3865
+ """The lasso by least angle regression, scikit-learn's
3866
+ _lars_path_solver with a Gram translated (method "lasso": variables
3867
+ leave the active set when their coefficient crosses zero, the
3868
+ Cholesky factor downdated by Givens rotations). ``LassoLars`` takes
3869
+ the Gram route for n > p; here it is taken always. ``alpha``
3870
+ defaults to 1.0 and ``max_iter`` to 500, as there.
3871
+
3872
+ Attributes after fit: coef_, intercept_, n_iter_.
3873
+ """
3874
+
3875
+ def __init__(self, alpha=1.0, *, max_iter=500, fit_intercept=True):
3876
+ self.alpha, self.max_iter, self.fit_intercept = alpha, max_iter, fit_intercept
3877
+
3878
+ def fit(self, X, y):
3879
+ return self._fit_lars(X, y, 1, float(self.alpha), int(self.max_iter))
3880
+
3881
+
3882
+ class _GramLarsCVBase(Tagged, RegressorMixin, BaseEstimator):
3883
+ """LarsCV / LassoLarsCV: KFold(cv) without shuffling; on each fold
3884
+ the whole path by the translated LARS over the training fold's Gram
3885
+ (centred on the training means), the test residuals interpolated
3886
+ onto the union of the folds' alphas as scikit-learn interpolates
3887
+ them (the path's coefficients interpolated, the residuals being
3888
+ affine in them, the mean square from the test fold's Gram); the
3889
+ alpha of the least mean square error, refitted on all the data."""
3890
+
3891
+ def __init__(self, *, fit_intercept=True, max_iter=500, cv=5, max_n_alphas=1000):
3892
+ self.fit_intercept, self.max_iter, self.cv = fit_intercept, max_iter, cv
3893
+ self.max_n_alphas = max_n_alphas
3894
+
3895
+ def _lars(self, Xc, yc, alpha_min, rec):
3896
+ n, p = Xc.shape
3897
+ G = _gram(Xc)
3898
+ cov = Xc.T @ yc
3899
+ coef = np.zeros(p)
3900
+ mi = int(self.max_iter)
3901
+ path = np.zeros((mi + 1, p)) if rec else np.zeros(1)
3902
+ alphas = np.zeros(mi + 1) if rec else np.zeros(1)
3903
+ it = _classifier_kernels().lars(G, cov, coef, path, alphas, 1 if rec else 0, float(n),
3904
+ float(alpha_min), self._method, mi,
3905
+ float(np.finfo(np.float64).eps), p)
3906
+ return it, coef, (path[:it + 1] if rec else None), (alphas[:it + 1] if rec else None)
3907
+
3908
+ def fit(self, X, y):
3909
+ X, y = fit_xy(self, X, y)
3910
+ n, p = X.shape
3911
+ if n < int(self.cv):
3912
+ raise ValueError(f"Cannot have number of splits n_splits={self.cv} greater than "
3913
+ f"the number of samples: n_samples={n}.")
3914
+ folds = []
3915
+ for train, test in _kfold(n, int(self.cv)):
3916
+ Xtr, ytr, Xte, yte = X[train], y[train], X[test], y[test]
3917
+ if self.fit_intercept:
3918
+ xm, ym = Xtr.mean(axis=0), ytr.mean()
3919
+ Xtr, Xte, ytr, yte = Xtr - xm, Xte - xm, ytr - ym, yte - ym
3920
+ _, _, path, alphas = self._lars(np.ascontiguousarray(Xtr), ytr, 0.0, True)
3921
+ folds.append((alphas, path, _gram(Xte), Xte.T @ yte, float(yte @ yte), len(test)))
3922
+ all_alphas = np.unique(np.concatenate([f[0] for f in folds]))
3923
+ stride = int(max(1, int(len(all_alphas) / float(self.max_n_alphas))))
3924
+ all_alphas = all_alphas[::stride]
3925
+ mse = np.empty((len(all_alphas), len(folds)))
3926
+ for j, (alphas, path, Gt, cyt, yy, nt) in enumerate(folds):
3927
+ a, c = alphas[::-1], path[::-1]
3928
+ if a[0] != 0:
3929
+ a, c = np.r_[0, a], np.r_[c[:1], c]
3930
+ if a[-1] != all_alphas[-1]:
3931
+ a, c = np.r_[a, all_alphas[-1]], np.r_[c, c[-1:]]
3932
+ ci = np.column_stack([np.interp(all_alphas, a, c[:, q]) for q in range(p)])
3933
+ mse[:, j] = (((ci @ Gt) * ci).sum(axis=1) - 2.0 * ci @ cyt + yy) / nt
3934
+ mask = np.all(np.isfinite(mse), axis=-1)
3935
+ all_alphas, mse = all_alphas[mask], mse[mask]
3936
+ self.alpha_ = float(all_alphas[int(np.argmin(mse.mean(axis=-1)))])
3937
+ self.cv_alphas_, self.mse_path_ = all_alphas, mse
3938
+ Xc, yc, xm, ym = _center(X, y, self.fit_intercept)
3939
+ self.n_iter_, self.coef_, _, _ = self._lars(Xc, yc, self.alpha_, False)
3940
+ self.intercept_ = ym - float(xm @ self.coef_)
3941
+ return self
3942
+
3943
+ def predict(self, X):
3944
+ return pred_x(self, X) @ self.coef_ + self.intercept_
3945
+
3946
+
3947
+ class GramLarsCV(_GramLarsCVBase):
3948
+ """scikit-learn's ``LarsCV`` (method "lar") over the translated LARS;
3949
+ see _GramLarsCVBase. Attributes after fit: alpha_, coef_, intercept_,
3950
+ cv_alphas_, mse_path_, n_iter_."""
3951
+ _method = 0
3952
+
3953
+
3954
+ class GramLassoLarsCV(_GramLarsCVBase):
3955
+ """scikit-learn's ``LassoLarsCV`` (method "lasso") over the translated
3956
+ LARS; see _GramLarsCVBase. Attributes after fit: alpha_, coef_,
3957
+ intercept_, cv_alphas_, mse_path_, n_iter_."""
3958
+ _method = 1
3959
+
3960
+
3961
+ class GramOMPCV(Tagged, RegressorMixin, BaseEstimator):
3962
+ """scikit-learn's ``OrthogonalMatchingPursuitCV``: KFold(cv) without
3963
+ shuffling; on each fold the path of the translated OMP (``omp.scm``,
3964
+ the path recorded) up to ``max_iter`` columns on the centred training
3965
+ fold, the test fold's mean square error after each column, the number
3966
+ of columns that minimises the folds' mean (over the shortest path),
3967
+ refitted as GramOMP. ``max_iter`` defaults, as there, to
3968
+ min(max(10% of p, 5), p).
3969
+
3970
+ Attributes after fit: n_nonzero_coefs_, coef_, intercept_, n_iter_.
3971
+ """
3972
+
3973
+ def __init__(self, *, fit_intercept=True, max_iter=None, cv=5):
3974
+ self.fit_intercept, self.max_iter, self.cv = fit_intercept, max_iter, cv
3975
+
3976
+ def fit(self, X, y):
3977
+ X, y = fit_xy(self, X, y)
3978
+ n, p = X.shape
3979
+ if n < int(self.cv):
3980
+ raise ValueError(f"Cannot have number of splits n_splits={self.cv} greater than "
3981
+ f"the number of samples: n_samples={n}.")
3982
+ kmax = min(max(int(0.1 * p), 5), p) if self.max_iter is None else int(self.max_iter)
3983
+ lib = _gramops_kernels()
3984
+ mses = []
3985
+ for train, test in _kfold(n, int(self.cv)):
3986
+ Xtr, ytr, Xte, yte = X[train], y[train], X[test], y[test]
3987
+ if self.fit_intercept:
3988
+ xm, ym = Xtr.mean(axis=0), ytr.mean()
3989
+ Xtr, Xte, ytr, yte = Xtr - xm, Xte - xm, ytr - ym, yte - ym
3990
+ path = np.zeros((kmax, p))
3991
+ k = lib.omp(np.ascontiguousarray(Xtr), np.ascontiguousarray(ytr), np.zeros(p),
3992
+ path, 1, kmax, len(train), p)
3993
+ res = Xte @ path[:k].T - yte[:, None]
3994
+ mses.append((res ** 2).mean(axis=0))
3995
+ m = min(len(f) for f in mses)
3996
+ best = int(np.argmin(np.mean([f[:m] for f in mses], axis=0))) + 1
3997
+ self.n_nonzero_coefs_ = best
3998
+ Xc, yc, xm, ym = _center(X, y, self.fit_intercept)
3999
+ self.coef_ = np.zeros(p)
4000
+ self.n_iter_ = lib.omp(Xc, yc, self.coef_, np.zeros(1), 0, best, n, p)
4001
+ self.intercept_ = ym - float(xm @ self.coef_)
4002
+ return self
4003
+
4004
+ def predict(self, X):
4005
+ return pred_x(self, X) @ self.coef_ + self.intercept_
4006
+
4007
+
4008
+ class GramLassoLarsIC(Tagged, RegressorMixin, BaseEstimator):
4009
+ """LassoLars with the penalty chosen by AIC or BIC, scikit-learn's
4010
+ ``LassoLarsIC``: the whole "lasso" path by the translated
4011
+ _lars_path_solver (``examples/kernel-only/lars.scm``, the path
4012
+ recorded as lars_path(return_path=True) returns it), then
4013
+ scikit-learn's criterion n log(2 pi s^2) + RSS / s^2 + K df at
4014
+ each knot, s^2 the OLS noise variance RSS_ols / (n - p - 1). The
4015
+ residual sums are taken from the Gram (|y - X c|^2 = y'y - 2 c'X'y
4016
+ + c'X'Xc, the OLS fit by its Cholesky factor) rather than from X
4017
+ at every knot as scikit-learn takes them -- the same numbers to
4018
+ rounding, without the n x knots product. n > p + 1, as there.
4019
+
4020
+ Attributes after fit: alpha_, coef_, intercept_, alphas_, criterion_,
4021
+ noise_variance_, n_iter_.
4022
+ """
4023
+
4024
+ def __init__(self, criterion="aic", *, fit_intercept=True, max_iter=500,
4025
+ noise_variance=None):
4026
+ self.criterion, self.fit_intercept, self.max_iter = criterion, fit_intercept, max_iter
4027
+ self.noise_variance = noise_variance
4028
+
4029
+ def fit(self, X, y):
4030
+ X, y = fit_xy(self, X, y)
4031
+ Xc, yc, xm, ym = _center(X, y, self.fit_intercept)
4032
+ n, p = Xc.shape
4033
+ mi = int(self.max_iter)
4034
+ G0 = _gram(Xc)
4035
+ cov0 = Xc.T @ yc
4036
+ yy = float(yc @ yc)
4037
+ path = np.zeros((mi + 1, p))
4038
+ alphas = np.zeros(mi + 1)
4039
+ coef = np.zeros(p)
4040
+ it = _classifier_kernels().lars(
4041
+ G0.copy(), cov0.copy(), coef, path, alphas, 1, float(n), 0.0, 1, mi,
4042
+ float(np.finfo(np.float64).eps), p)
4043
+ cp, al = path[:it + 1], alphas[:it + 1]
4044
+ rss = yy - 2.0 * (cp @ cov0) + ((cp @ G0) * cp).sum(axis=1)
4045
+ df = (np.abs(cp) > np.finfo(np.float64).eps).sum(axis=1)
4046
+ if self.noise_variance is None:
4047
+ if n <= p + int(self.fit_intercept):
4048
+ raise ValueError(f"n must exceed p (+1 with an intercept) to estimate the "
4049
+ f"noise variance; got n_samples = {n} for {p} features; "
4050
+ "pass noise_variance")
4051
+ L = np.linalg.cholesky(G0)
4052
+ beta = np.linalg.solve(L.T, np.linalg.solve(L, cov0))
4053
+ self.noise_variance_ = (yy - 2.0 * beta @ cov0 + beta @ G0 @ beta) / (
4054
+ n - p - int(self.fit_intercept))
4055
+ else:
4056
+ self.noise_variance_ = float(self.noise_variance)
4057
+ factor = {"aic": 2.0, "bic": np.log(n)}[self.criterion]
4058
+ self.criterion_ = (n * np.log(2 * np.pi * self.noise_variance_)
4059
+ + rss / self.noise_variance_ + factor * df)
4060
+ best = int(np.argmin(self.criterion_))
4061
+ self.alphas_, self.n_iter_ = al, it
4062
+ self.alpha_ = float(al[best])
4063
+ self.coef_ = cp[best].copy()
4064
+ self.intercept_ = ym - float(xm @ self.coef_)
4065
+ return self
4066
+
4067
+ def predict(self, X):
4068
+ return pred_x(self, X) @ self.coef_ + self.intercept_
4069
+
4070
+
4071
+ class WeiszfeldTheilSen(Tagged, RegressorMixin, BaseEstimator):
4072
+ """scikit-learn's ``TheilSenRegressor`` translated whole
4073
+ (``examples/kernel-only/theilsen.scm``): the least squares fit of
4074
+ every subset of n_subsamples rows (p + 1 by default: each an exact
4075
+ solve, the minimum-norm fit for a singular one, as gelss gives it)
4076
+ and the spatial median of the fits by the modified Weiszfeld
4077
+ iteration. The subsets are scikit-learn's: all the combinations
4078
+ when there are at most ``max_subpopulation``, else
4079
+ ``RandomState(random_state).choice`` draws, made here the same way
4080
+ (and on large problems that drawing is most of the time, on both
4081
+ sides).
4082
+
4083
+ Attributes after fit: coef_, intercept_, n_iter_, n_subpopulation_,
4084
+ breakdown_.
4085
+ """
4086
+
4087
+ def __init__(self, *, fit_intercept=True, max_subpopulation=1e4, n_subsamples=None,
4088
+ max_iter=300, tol=1e-3, random_state=None):
4089
+ self.fit_intercept, self.max_subpopulation = fit_intercept, max_subpopulation
4090
+ self.n_subsamples, self.max_iter, self.tol = n_subsamples, max_iter, tol
4091
+ self.random_state = random_state
4092
+
4093
+ def fit(self, X, y):
4094
+ from itertools import combinations
4095
+ from math import comb
4096
+ X, y = fit_xy(self, X, y)
4097
+ n, p = X.shape
4098
+ fi = 1 if self.fit_intercept else 0
4099
+ ns = min(p + fi, n) if self.n_subsamples is None else int(self.n_subsamples)
4100
+ total = max(1, comb(n, ns))
4101
+ self.n_subpopulation_ = int(min(self.max_subpopulation, total))
4102
+ self.breakdown_ = 1 - (0.5 ** (1 / ns) * (n - ns + 1) + ns - 1) / n
4103
+ if total <= self.max_subpopulation:
4104
+ idx = np.array(list(combinations(range(n), ns)), dtype=np.int32)
4105
+ else:
4106
+ rs = np.random.RandomState(self.random_state)
4107
+ idx = np.array([rs.choice(n, size=ns, replace=False)
4108
+ for _ in range(self.n_subpopulation_)], dtype=np.int32)
4109
+ nsub = len(idx)
4110
+ w = np.zeros((nsub, p + fi))
4111
+ c = np.zeros(p + fi)
4112
+ self.n_iter_ = _classifier_kernels().theilsen(X, y, idx, w, c, nsub, ns, fi,
4113
+ int(self.max_iter), float(self.tol), p)
4114
+ self.intercept_ = float(c[0]) if fi else 0.0
4115
+ self.coef_ = c[fi:].copy()
4116
+ return self
4117
+
4118
+ def predict(self, X):
4119
+ return pred_x(self, X) @ self.coef_ + self.intercept_
4120
+
4121
+
4122
+ class L1LinearSVM(Tagged, ClassifierMixin, BaseEstimator):
4123
+ """The L1-regularized L2-loss linear SVM by liblinear's own
4124
+ algorithm: ``examples/kernel-only/svm-l1.scm`` translated plainly,
4125
+ liblinear's solve_l1r_l2_svc (coordinate descent with a Newton step,
4126
+ a line search and shrinking) -- what scikit-learn's
4127
+ ``LinearSVC(penalty="l1", dual=False)`` runs, on
4128
+
4129
+ min_w sum_j |w_j| + C sum_i max(0, 1 - y_i w.x_i)^2,
4130
+
4131
+ the intercept a ones column (``intercept_scaling``) penalised with
4132
+ the rest, as liblinear has it. The coordinate order is random from
4133
+ a different generator than liblinear's, so the fit agrees with
4134
+ scikit-learn's to its tolerance. Two classes.
4135
+
4136
+ Attributes after fit: classes_, coef_, intercept_, n_iter_.
4137
+ """
4138
+
4139
+ def __init__(self, C=1.0, tol=1e-4, max_iter=1000, fit_intercept=True,
4140
+ intercept_scaling=1.0, random_state=0):
4141
+ self.C, self.tol, self.max_iter = C, tol, max_iter
4142
+ self.fit_intercept, self.intercept_scaling = fit_intercept, intercept_scaling
4143
+ self.random_state = random_state
4144
+
4145
+ _binary_only = True
4146
+
4147
+ def fit(self, X, y):
4148
+ X, y = fit_xy(self, X, y, classifier=True)
4149
+ n, p = X.shape
4150
+ self.classes_, ys = _binary_labels(y)
4151
+ scaling = float(self.intercept_scaling)
4152
+ if self.fit_intercept:
4153
+ X = np.hstack([X, np.full((n, 1), scaling)])
4154
+ q = X.shape[1]
4155
+ w = np.zeros(q)
4156
+ # liblinear walks the design by columns
4157
+ self.n_iter_ = _classifier_kernels().svm_l1(
4158
+ np.ascontiguousarray(X.T), ys, w, float(self.C), float(self.tol), int(self.max_iter),
4159
+ _seed(self.random_state), n, q)
4160
+ self.coef_ = w[:p].copy()
4161
+ self.intercept_ = float(w[p] * scaling) if self.fit_intercept else 0.0
4162
+ return self
4163
+
4164
+ def decision_function(self, X):
4165
+ return pred_x(self, X) @ self.coef_ + self.intercept_
4166
+
4167
+ def predict(self, X):
4168
+ z = self.decision_function(X)
4169
+ return self.classes_[(z > 0).astype(int)]
4170
+
4171
+
4172
+ class L1LogisticRegression(Tagged, ClassifierMixin, BaseEstimator):
4173
+ """L1-regularized logistic regression by liblinear's own algorithm.
4174
+
4175
+ ``examples/kernel-only/logistic-l1.scm`` translated plainly:
4176
+ liblinear's solve_l1r_lr (newGLMNET: Newton iterations over a
4177
+ coordinate-descent subproblem with random order and shrinking, and
4178
+ a line search) -- what scikit-learn's
4179
+ ``LogisticRegression(l1_ratio=1, solver="liblinear",
4180
+ fit_intercept=False)`` runs, on the same problem
4181
+
4182
+ min_w sum_j |w_j| + C sum_i log(1 + exp(-y_i w.x_i)).
4183
+
4184
+ ``tol`` and ``max_iter`` are LogisticRegression's (the tolerance is
4185
+ scaled as liblinear scales it; the cap counts Newton iterations).
4186
+ No intercept; two classes. ``CovLogistic`` solves the same problem
4187
+ by majorization over the Gram matrix instead.
4188
+
4189
+ Attributes after fit: classes_, coef_, n_iter_.
4190
+ """
4191
+
4192
+ _binary_only = True
4193
+
4194
+ def __init__(self, C=1.0, tol=1e-4, max_iter=100, random_state=0):
4195
+ self.C, self.tol, self.max_iter = C, tol, max_iter
4196
+ self.random_state = random_state
4197
+
4198
+ def fit(self, X, y):
4199
+ X, y = fit_xy(self, X, y, classifier=True)
4200
+ n, p = X.shape
4201
+ self.classes_, ys = _binary_labels(y)
4202
+ w = np.zeros(p)
4203
+ # liblinear walks the design by columns
4204
+ self.n_iter_ = _classifier_kernels().logistic_l1(
4205
+ np.ascontiguousarray(X.T), ys, w, float(self.C), float(self.tol), int(self.max_iter),
4206
+ _seed(self.random_state), n, p)
4207
+ self.coef_ = w
4208
+ self.intercept_ = 0.0
4209
+ return self
4210
+
4211
+ def decision_function(self, X):
4212
+ return pred_x(self, X) @ self.coef_
4213
+
4214
+ def predict_proba(self, X):
4215
+ p1 = 1.0 / (1.0 + np.exp(-self.decision_function(X)))
4216
+ return np.column_stack([1.0 - p1, p1])
4217
+
4218
+ def predict(self, X):
4219
+ z = self.decision_function(X)
4220
+ return self.classes_[(z > 0).astype(int)]
4221
+
4222
+
4223
+ class CovLogistic:
4224
+ """L1-penalized logistic regression, by majorization over the Gram.
4225
+
4226
+ The objective is
4227
+
4228
+ (1/n) sum_i [log(1 + exp(eta_i)) - y_i eta_i] + lam ||b||_1
4229
+
4230
+ with eta = X b and y in {0,1} -- scikit-learn's ``LogisticRegression``
4231
+ with ``penalty="l1"``, ``fit_intercept=False`` and ``C = 1/(n lam)``.
4232
+
4233
+ The logistic Hessian is bounded by X'X / 4 (Bohning's bound), so
4234
+ instead of reweighting the Gram matrix every round -- which would
4235
+ cost O(n p^2) each time and break the design-free construction --
4236
+ the quadratic term is fixed at G/4 once and only the gradient
4237
+ moves. Each outer round costs one pass for eta and one for
4238
+ X'(y - mu), then hands the majorizer to the same coordinate
4239
+ descent the lasso uses: warm-started, exactly resumable, and with
4240
+ the pleasant identity that the working correlations are exactly
4241
+ X'(y - mu). Majorization descends monotonically to the optimum
4242
+ of this convex problem.
4243
+ """
4244
+
4245
+ def __init__(self, X, y):
4246
+ X = np.ascontiguousarray(X, dtype=np.float64)
4247
+ y = np.ascontiguousarray(y, dtype=np.float64)
4248
+ if X.ndim != 2 or y.ndim != 1 or X.shape[0] != y.size:
4249
+ raise ValueError(
4250
+ f"X is {X.shape} and y is {y.shape}; expected (n, p) "
4251
+ "and (n,)")
4252
+ if not np.all((y == 0.0) | (y == 1.0)):
4253
+ raise ValueError("y must be 0/1")
4254
+ self.X, self.y = X, y
4255
+ self.nobs, self.p = X.shape
4256
+ self.g4 = np.ascontiguousarray((X.T @ X).ravel() / 4.0)
4257
+
4258
+ def _grad_corr(self, beta):
4259
+ mu = 1.0 / (1.0 + np.exp(-(self.X @ beta)))
4260
+ return self.X.T @ (self.y - mu)
4261
+
4262
+ def lambda_max(self):
4263
+ """The smallest penalty keeping every coefficient at zero.
4264
+
4265
+ At beta = 0 the gradient is X'(y - 1/2); the penalty must beat
4266
+ its largest entry, scaled as the objective is.
4267
+ """
4268
+ return float(np.max(np.abs(self.X.T @ (self.y - 0.5)))) / self.nobs
4269
+
4270
+ def lambda_grid(self, num=50, eps=1e-2):
4271
+ """A log-spaced descending path from lambda_max."""
4272
+ return self.lambda_max() * np.logspace(0, np.log10(eps), int(num))
4273
+
4274
+ def fit_path(self, lambdas, tol=1e-7, inner_sweeps=200,
4275
+ max_rounds=500):
4276
+ """Coefficients per lambda, warm-started down the path."""
4277
+ lambdas = np.asarray(lambdas, dtype=np.float64)
4278
+ beta = np.zeros(self.p)
4279
+ out = np.empty((lambdas.size, self.p))
4280
+ for i, lam in enumerate(lambdas):
4281
+ beta = self._fit_one(beta, float(lam), tol, inner_sweeps,
4282
+ max_rounds)
4283
+ out[i] = beta
4284
+ return out
4285
+
4286
+ def fit(self, lam, **kw):
4287
+ """Coefficients at one lambda, from zero."""
4288
+ return self._fit_one(np.zeros(self.p), float(lam),
4289
+ kw.get("tol", 1e-7),
4290
+ kw.get("inner_sweeps", 200),
4291
+ kw.get("max_rounds", 500))
4292
+
4293
+ def _fit_one(self, beta, lam, tol, inner_sweeps, max_rounds):
4294
+ beta = beta.copy()
4295
+ self._rounds = 0
4296
+ for _ in range(max_rounds):
4297
+ self._rounds += 1
4298
+ prev = beta.copy()
4299
+ # the majorizer at beta: quadratic G/4, working
4300
+ # correlations exactly X'(y - mu)
4301
+ c = np.ascontiguousarray(self._grad_corr(beta))
4302
+ kernel.cov_descend(self.g4, c, beta, lam, inner_sweeps,
4303
+ float(self.nobs), self.p)
4304
+ if np.max(np.abs(beta - prev)) < tol * max(
4305
+ 1.0, float(np.max(np.abs(beta)))):
4306
+ break
4307
+ return beta
4308
+
4309
+
4310
+ class GramLogisticRegression(Tagged, ClassifierMixin, BaseEstimator):
4311
+ """scikit-learn's ``LogisticRegression(l1_ratio=1, solver="liblinear")``
4312
+ interface over CovLogistic: the same problem,
4313
+
4314
+ min_w ||w||_1 + C sum_i log(1 + exp(-y_i (w.x_i + b))),
4315
+
4316
+ solved by majorization over the Gram matrix instead of liblinear's
4317
+ Newton steps. As in liblinear the intercept is the weight of a
4318
+ constant column of value ``intercept_scaling`` and is penalized
4319
+ with the rest. ``tol`` is CovLogistic's (the largest coefficient
4320
+ move in a round, relative to their size) and ``max_iter`` caps the
4321
+ rounds. Two classes.
4322
+
4323
+ Attributes after fit: classes_, coef_, intercept_, n_iter_.
4324
+ """
4325
+
4326
+ _binary_only = True
4327
+
4328
+ def __init__(self, C=1.0, *, fit_intercept=True, intercept_scaling=1.0, tol=1e-7,
4329
+ max_iter=500):
4330
+ self.C, self.fit_intercept, self.intercept_scaling = C, fit_intercept, intercept_scaling
4331
+ self.tol, self.max_iter = tol, max_iter
4332
+
4333
+ def fit(self, X, y):
4334
+ X, y = fit_xy(self, X, y, classifier=True)
4335
+ n = X.shape[0]
4336
+ self.classes_, ys = _binary_labels(y)
4337
+ s = float(self.intercept_scaling)
4338
+ if self.fit_intercept:
4339
+ X = np.column_stack([X, np.full(n, s)])
4340
+ m = CovLogistic(X, (ys > 0).astype(np.float64))
4341
+ lam = 1.0 / (n * float(self.C))
4342
+ beta = m._fit_one(np.zeros(m.p), lam, float(self.tol), 200, int(self.max_iter))
4343
+ self.n_iter_ = m._rounds
4344
+ if self.fit_intercept:
4345
+ self.coef_, self.intercept_ = beta[:-1].copy(), float(beta[-1]) * s
4346
+ else:
4347
+ self.coef_, self.intercept_ = beta, 0.0
4348
+ return self
4349
+
4350
+ def decision_function(self, X):
4351
+ return pred_x(self, X) @ self.coef_ + self.intercept_
4352
+
4353
+ def predict_proba(self, X):
4354
+ p1 = 1.0 / (1.0 + np.exp(-self.decision_function(X)))
4355
+ return np.column_stack([1.0 - p1, p1])
4356
+
4357
+ def predict(self, X):
4358
+ z = self.decision_function(X)
4359
+ return self.classes_[(z > 0).astype(int)]
4360
+
4361
+
4362
+ class CovGroupLasso:
4363
+ """Group lasso over a design given by its Gram matrix.
4364
+
4365
+ The objective groups the penalty:
4366
+
4367
+ (1/2n) ||y - X b||^2 + lam * sum_g w_g ||b_g||_2
4368
+
4369
+ with the usual weights w_g = sqrt(|g|), so whole groups enter or
4370
+ leave together. Block coordinate descent runs on the Gram matrix
4371
+ exactly as the lasso's coordinate descent does -- the working
4372
+ correlations c = X'y - G b are maintained across visits -- and
4373
+ each block visit is one majorized proximal step: the group's Gram
4374
+ block is dominated by its top eigenvalue L_g (found once), and the
4375
+ resulting subproblem has the group soft-threshold in closed form.
4376
+ Majorization descends monotonically; a group of size one reduces
4377
+ exactly to the lasso's coordinate update.
4378
+
4379
+ ``groups`` is a list of index arrays, a partition of 0..p-1.
4380
+ """
4381
+
4382
+ def __init__(self, X=None, y=None, *, gram=None, corr=None,
4383
+ nobs=None, groups=None):
4384
+ if gram is not None:
4385
+ if corr is None or nobs is None:
4386
+ raise ValueError("gram needs corr and nobs alongside it")
4387
+ g = np.ascontiguousarray(gram, dtype=np.float64)
4388
+ c = np.ascontiguousarray(corr, dtype=np.float64)
4389
+ self.p = c.size
4390
+ self.G = g.reshape(self.p, self.p)
4391
+ self.c0, self.nobs = c, int(nobs)
4392
+ else:
4393
+ if X is None or y is None:
4394
+ raise ValueError("pass X and y, or gram, corr and nobs")
4395
+ X = np.ascontiguousarray(X, dtype=np.float64)
4396
+ y = np.ascontiguousarray(y, dtype=np.float64)
4397
+ self.nobs, self.p = X.shape
4398
+ self.G = X.T @ X
4399
+ self.c0 = X.T @ y
4400
+ if groups is None:
4401
+ raise ValueError("groups is required")
4402
+ self.groups = [np.asarray(g, dtype=np.intp) for g in groups]
4403
+ seen = np.concatenate(self.groups)
4404
+ if sorted(seen.tolist()) != list(range(self.p)):
4405
+ raise ValueError("groups must partition 0..p-1")
4406
+ self.wg = np.array([np.sqrt(len(g)) for g in self.groups])
4407
+ # the majorizer per group: its Gram block's top eigenvalue
4408
+ self.Lg = np.array(
4409
+ [float(np.linalg.eigvalsh(self.G[np.ix_(g, g)])[-1])
4410
+ for g in self.groups])
4411
+
4412
+ def lambda_max(self):
4413
+ """The smallest penalty at which every group stays zero."""
4414
+ return max(float(np.linalg.norm(self.c0[g])) / (self.nobs * w)
4415
+ for g, w in zip(self.groups, self.wg))
4416
+
4417
+ def lambda_grid(self, num=50, eps=1e-2):
4418
+ """A log-spaced descending path from lambda_max."""
4419
+ return self.lambda_max() * np.logspace(0, np.log10(eps), int(num))
4420
+
4421
+ def fit_path(self, lambdas, tol=1e-8, max_sweeps=10000):
4422
+ """Coefficients per lambda, warm-started down the path."""
4423
+ lambdas = np.asarray(lambdas, dtype=np.float64)
4424
+ beta = np.zeros(self.p)
4425
+ c = self.c0.copy()
4426
+ out = np.empty((lambdas.size, self.p))
4427
+ for i, lam in enumerate(lambdas):
4428
+ beta, c = self._fit_one(beta, c, float(lam), tol, max_sweeps)
4429
+ out[i] = beta
4430
+ return out
4431
+
4432
+ def fit(self, lam, **kw):
4433
+ """Coefficients at one lambda, from zero."""
4434
+ b, _ = self._fit_one(np.zeros(self.p), self.c0.copy(), float(lam),
4435
+ kw.get("tol", 1e-8),
4436
+ kw.get("max_sweeps", 10000))
4437
+ return b
4438
+
4439
+ def _fit_one(self, beta, c, lam, tol, max_sweeps):
4440
+ thr = lam * self.nobs
4441
+ self._sweeps = 0
4442
+ for _ in range(max_sweeps):
4443
+ self._sweeps += 1
4444
+ moved = 0.0
4445
+ for g, w, L in zip(self.groups, self.wg, self.Lg):
4446
+ if L <= 0.0: # all-zero columns: the group stays at zero
4447
+ continue
4448
+ bg = beta[g]
4449
+ z = bg + c[g] / L
4450
+ nz = float(np.linalg.norm(z))
4451
+ scale = max(0.0, 1.0 - thr * w / (L * nz)) if nz > 0 else 0.0
4452
+ nb = scale * z
4453
+ d = nb - bg
4454
+ dmax = float(np.max(np.abs(d))) if d.size else 0.0
4455
+ if dmax > 0.0:
4456
+ c -= self.G[:, g] @ d
4457
+ beta[g] = nb
4458
+ moved = max(moved, dmax)
4459
+ if moved < tol * max(1.0, float(np.max(np.abs(beta)))):
4460
+ break
4461
+ return beta, c
4462
+
4463
+ def objective(self, y_or_none, beta, lam):
4464
+ """The penalized objective, up to the constant ||y||^2/(2n).
4465
+
4466
+ Computable from the Gram alone: (1/2n)(b'Gb - 2 c0'b) plus the
4467
+ penalty; add ||y||^2/(2n) yourself if you want the absolute
4468
+ value.
4469
+ """
4470
+ quad = 0.5 * (beta @ self.G @ beta) - self.c0 @ beta
4471
+ pen = sum(w * float(np.linalg.norm(beta[g]))
4472
+ for g, w in zip(self.groups, self.wg))
4473
+ return quad / self.nobs + lam * pen
4474
+
4475
+
4476
+ class GramGroupLasso(Tagged, RegressorMixin, BaseEstimator):
4477
+ """A ``Lasso``-style interface over CovGroupLasso: fit(X, y) centres
4478
+ the data when ``fit_intercept`` and runs the block descent at
4479
+ ``alpha``,
4480
+
4481
+ (1 / 2 n) ||y - X b - b0||^2 + alpha sum_g sqrt(|g|) ||b_g||_2.
4482
+
4483
+ ``groups`` is a list of index arrays partitioning the columns, or
4484
+ None for one group per column (the lasso). ``tol`` is
4485
+ CovGroupLasso's and ``max_iter`` its sweep cap.
4486
+
4487
+ Attributes after fit: coef_, intercept_, n_iter_, n_features_in_.
4488
+ """
4489
+
4490
+ def __init__(self, alpha=1.0, *, groups=None, fit_intercept=True, tol=1e-8,
4491
+ max_iter=10000):
4492
+ self.alpha, self.groups, self.fit_intercept = alpha, groups, fit_intercept
4493
+ self.tol, self.max_iter = tol, max_iter
4494
+
4495
+ def fit(self, X, y):
4496
+ X, y = fit_xy(self, X, y)
4497
+ n, p = X.shape
4498
+ G, c, xm, ym = _centered_gram(X, y, self.fit_intercept)
4499
+ groups = [[j] for j in range(p)] if self.groups is None else self.groups
4500
+ m = CovGroupLasso(gram=G, corr=c, nobs=n, groups=groups)
4501
+ beta, _ = m._fit_one(np.zeros(p), m.c0.copy(), float(self.alpha), float(self.tol),
4502
+ int(self.max_iter))
4503
+ self.coef_, self.n_iter_ = beta, m._sweeps
4504
+ self.intercept_ = float(ym - xm @ self.coef_)
4505
+ return self
4506
+
4507
+ def predict(self, X):
4508
+ return pred_x(self, X) @ self.coef_ + self.intercept_
4509
+
4510
+
4511
+ class CovMultiTaskLasso:
4512
+ """Multi-task lasso and elastic net over a design's Gram matrix.
4513
+
4514
+ The penalty ties each feature's row of W together across tasks --
4515
+ the row enters or leaves for every task at once -- matching
4516
+ scikit-learn's ``MultiTaskLasso`` / ``MultiTaskElasticNet`` with
4517
+ ``fit_intercept=False``:
4518
+
4519
+ (1/2n)||Y - XW||^2_F + alpha l1_ratio sum_j ||W_j||_2
4520
+ + (alpha/2)(1 - l1_ratio) ||W||^2_F
4521
+
4522
+ The covariance route carries over unchanged: the solver keeps
4523
+ C = X'Y - G W per task, so a row's block update is O(p T) and never
4524
+ touches the n rows. Coefficients are (p, n_tasks) -- the transpose
4525
+ of scikit-learn's ``coef_``.
4526
+ """
4527
+
4528
+ def __init__(self, X=None, Y=None, *, gram=None, corr=None, nobs=None):
4529
+ if gram is not None:
4530
+ if corr is None or nobs is None:
4531
+ raise ValueError("gram needs corr and nobs alongside it")
4532
+ c = np.ascontiguousarray(corr, dtype=np.float64)
4533
+ if c.ndim != 2:
4534
+ raise ValueError("corr must be (p, n_tasks)")
4535
+ self.p, self.n_tasks = c.shape
4536
+ g = np.ascontiguousarray(gram, dtype=np.float64).ravel()
4537
+ if g.size != self.p * self.p:
4538
+ raise ValueError(f"gram is {g.size} entries; expected p*p")
4539
+ self.nobs, self.g, self.c0 = int(nobs), g, c.ravel()
4540
+ else:
4541
+ if X is None or Y is None:
4542
+ raise ValueError("pass X and Y, or gram, corr and nobs")
4543
+ X = np.ascontiguousarray(X, dtype=np.float64)
4544
+ Y = np.ascontiguousarray(Y, dtype=np.float64)
4545
+ if Y.ndim != 2 or X.shape[0] != Y.shape[0]:
4546
+ raise ValueError(
4547
+ f"X is {X.shape} and Y is {Y.shape}; expected (n, p) "
4548
+ "and (n, n_tasks)")
4549
+ self.nobs, self.p = X.shape
4550
+ self.n_tasks = Y.shape[1]
4551
+ self.g = np.ascontiguousarray((X.T @ X).ravel())
4552
+ self.c0 = np.ascontiguousarray((X.T @ Y).ravel())
4553
+ self.X, self.Y = X, Y
4554
+
4555
+ def lambda_max(self, l1_ratio=1.0):
4556
+ """The smallest penalty that zeroes every row of W.
4557
+
4558
+ The single-task |X_j'y| becomes the L2 norm of the row X_j'Y:
4559
+ below it the block soft threshold leaves the row at zero.
4560
+ """
4561
+ C = self.c0.reshape(self.p, self.n_tasks)
4562
+ return (float(np.max(np.linalg.norm(C, axis=1)))
4563
+ / (self.nobs * l1_ratio))
4564
+
4565
+ def lambda_grid(self, num=100, eps=1e-3, l1_ratio=1.0):
4566
+ """Log-spaced from lambda_max down, as the single-task grid is."""
4567
+ hi = self.lambda_max(l1_ratio)
4568
+ return hi * np.logspace(0, np.log10(eps), int(num))
4569
+
4570
+ def fit(self, lam, **kw):
4571
+ """Coefficients (p, n_tasks) at one penalty."""
4572
+ return self.fit_path([lam], **kw)[0]
4573
+
4574
+ def fit_path(self, lambdas, tol=1e-8, chunk=20, max_sweeps=100000,
4575
+ l1_ratio=1.0):
4576
+ """Coefficients per lambda, warm-started; (len(lambdas), p, n_tasks).
4577
+
4578
+ Give lambdas in descending order, as with the single-task path.
4579
+ """
4580
+ lambdas = np.asarray(lambdas, dtype=np.float64)
4581
+ pt = self.p * self.n_tasks
4582
+ W, c = np.zeros(pt), self.c0.copy()
4583
+ prev = np.empty(pt)
4584
+ out = np.empty((lambdas.size, self.p, self.n_tasks))
4585
+ for i, lam in enumerate(lambdas):
4586
+ swept = 0
4587
+ while swept < max_sweeps:
4588
+ prev[:] = W
4589
+ kernel.mt_descend(self.g, c, W,
4590
+ float(lam) * l1_ratio,
4591
+ float(lam) * (1.0 - l1_ratio), chunk,
4592
+ float(self.nobs), self.p, self.n_tasks)
4593
+ swept += chunk
4594
+ if np.max(np.abs(W - prev)) < tol * _scale(W):
4595
+ break
4596
+ out[i] = W.reshape(self.p, self.n_tasks)
4597
+ return out
4598
+
4599
+ def fit_path_batch(self, lambdas, tol=1e-8, chunk=20,
4600
+ max_sweeps=100000, force_cpu=False, l1_ratio=1.0):
4601
+ """Coefficients per lambda, every lambda solved from zero.
4602
+
4603
+ (len(lambdas), p, n_tasks). On the GPU one block per lambda,
4604
+ all sharing this Gram; the CPU fallback is the cold loop.
4605
+ """
4606
+ lambdas = np.ascontiguousarray(lambdas, dtype=np.float64)
4607
+ pt = self.p * self.n_tasks
4608
+ if not force_cpu:
4609
+ W = _grid_descend(self.g[None, :], self.c0[None, :], lambdas,
4610
+ self.p, self.n_tasks, tol=tol, chunk=chunk,
4611
+ max_sweeps=max_sweeps, l1_ratio=l1_ratio,
4612
+ nobs=float(self.nobs))
4613
+ if W is not None:
4614
+ return W.reshape(lambdas.size, self.p, self.n_tasks)
4615
+ out = np.empty((lambdas.size, pt))
4616
+ prev = np.empty(pt)
4617
+ for i, lam in enumerate(lambdas):
4618
+ W, c, swept = np.zeros(pt), self.c0.copy(), 0
4619
+ while swept < max_sweeps:
4620
+ prev[:] = W
4621
+ kernel.mt_descend(self.g, c, W, float(lam) * l1_ratio,
4622
+ float(lam) * (1.0 - l1_ratio), chunk,
4623
+ float(self.nobs), self.p, self.n_tasks)
4624
+ swept += chunk
4625
+ if np.max(np.abs(W - prev)) < tol * _scale(W):
4626
+ break
4627
+ out[i] = W
4628
+ return out.reshape(lambdas.size, self.p, self.n_tasks)
4629
+
4630
+
4631
+ class GramMultiTaskElasticNet(Tagged, RegressorMixin, BaseEstimator):
4632
+ """scikit-learn's ``MultiTaskElasticNet`` interface over
4633
+ CovMultiTaskLasso: fit(X, Y) centres the data when
4634
+ ``fit_intercept``, forms the Gram matrix once and runs the row-block
4635
+ sweep at ``alpha``. Y is (n, n_tasks); coef_ is (n_tasks, p) as
4636
+ scikit-learn has it. ``tol`` is CovMultiTaskLasso's and
4637
+ ``max_iter`` its sweep cap.
4638
+
4639
+ Attributes after fit: coef_, intercept_, n_iter_, n_features_in_.
4640
+ """
4641
+
4642
+ _multi_output = "only"
4643
+
4644
+ def __init__(self, alpha=1.0, *, l1_ratio=0.5, fit_intercept=True, tol=1e-8,
4645
+ max_iter=100000):
4646
+ self.alpha, self.l1_ratio, self.fit_intercept = alpha, l1_ratio, fit_intercept
4647
+ self.tol, self.max_iter = tol, max_iter
4648
+
4649
+ def fit(self, X, y):
4650
+ X, y = fit_xy(self, X, y, multi_output=True)
4651
+ if y.ndim != 2:
4652
+ raise ValueError("For mono-task outputs, use GramElasticNet or GramLasso; "
4653
+ "y must be (n_samples, n_tasks)")
4654
+ n, p = X.shape
4655
+ t = y.shape[1]
4656
+ G, c, xm, ym = _centered_gram(X, y, self.fit_intercept)
4657
+ g = np.ascontiguousarray(G.ravel())
4658
+ c = np.ascontiguousarray(c.ravel())
4659
+ lam, r = float(self.alpha), float(self.l1_ratio)
4660
+ tol, cap = float(self.tol), int(self.max_iter)
4661
+ W, prev = np.zeros(p * t), np.empty(p * t)
4662
+ swept = 0
4663
+ while swept < cap:
4664
+ chunk = min(20, cap - swept)
4665
+ prev[:] = W
4666
+ kernel.mt_descend(g, c, W, lam * r, lam * (1.0 - r), chunk, float(n), p, t)
4667
+ swept += chunk
4668
+ if np.max(np.abs(W - prev)) < tol * _scale(W):
4669
+ break
4670
+ W = W.reshape(p, t)
4671
+ self.coef_, self.n_iter_ = np.ascontiguousarray(W.T), swept
4672
+ self.intercept_ = ym - xm @ W
4673
+ return self
4674
+
4675
+ def predict(self, X):
4676
+ return pred_x(self, X) @ self.coef_.T + self.intercept_
4677
+
4678
+
4679
+ class GramMultiTaskLasso(GramMultiTaskElasticNet):
4680
+ """scikit-learn's ``MultiTaskLasso`` interface over CovMultiTaskLasso:
4681
+ GramMultiTaskElasticNet with l1_ratio 1.
4682
+
4683
+ Attributes after fit: coef_, intercept_, n_iter_, n_features_in_.
4684
+ """
4685
+
4686
+ def __init__(self, alpha=1.0, *, fit_intercept=True, tol=1e-8, max_iter=100000):
4687
+ self.alpha, self.fit_intercept, self.tol, self.max_iter = alpha, fit_intercept, tol, max_iter
4688
+
4689
+ @property
4690
+ def l1_ratio(self):
4691
+ return 1.0
4692
+
4693
+
4694
+ class CovMultiTaskLassoCV(Tagged, RegressorMixin, BaseEstimator):
4695
+ """scikit-learn's ``MultiTaskLassoCV`` (``MultiTaskElasticNetCV``
4696
+ with ``l1_ratio``) over the covariance machinery.
4697
+
4698
+ Same construction as ``CovLassoCV``: the grid from the full data,
4699
+ contiguous folds, each fold's training Gram a subtraction from the
4700
+ full one, the whole path walked warm per fold, alpha_ by minimum
4701
+ mean validation MSE (over samples and tasks) with ties to the
4702
+ larger penalty, refit on all rows. With a GPU the grid is one
4703
+ launch, one block per (fold, penalty) problem, as in CovLassoCV.
4704
+
4705
+ Attributes after fit: alphas_, mse_path_ (num, cv), alpha_, coef_
4706
+ (p, n_tasks).
4707
+ """
4708
+
4709
+ _multi_output = "only"
4710
+
4711
+ def __init__(self, cv=5, num=100, eps=1e-3, tol=1e-8, l1_ratio=1.0,
4712
+ force_cpu=False, force_gpu=False, n_jobs=1):
4713
+ # Same fold-thread parallelism as CovLassoCV; default sequential.
4714
+ self.cv, self.num, self.eps, self.tol = cv, num, eps, tol
4715
+ self.l1_ratio, self.force_cpu, self.force_gpu = l1_ratio, force_cpu, force_gpu
4716
+ self.n_jobs = n_jobs
4717
+
4718
+ def fit(self, X, Y):
4719
+ X, Y = fit_xy(self, X, Y, multi_output=True)
4720
+ if Y.ndim != 2:
4721
+ raise ValueError("For mono-task outputs, use CovLassoCV; Y must be (n, n_tasks)")
4722
+ n = X.shape[0]
4723
+ cv, num = int(self.cv), int(self.num)
4724
+ tol, l1_ratio = float(self.tol), float(self.l1_ratio)
4725
+ full = CovMultiTaskLasso(X, Y)
4726
+ self.alphas_ = full.lambda_grid(num=num, eps=float(self.eps),
4727
+ l1_ratio=l1_ratio)
4728
+ bounds = np.linspace(0, n, cv + 1).astype(int)
4729
+ self.mse_path_ = np.empty((num, cv))
4730
+ G = full.g.reshape(full.p, full.p)
4731
+ C = full.c0.reshape(full.p, full.n_tasks)
4732
+ if cuda_available() and not self.force_cpu:
4733
+ done = self._fit_gpu(X, Y, full, G, C, bounds, n)
4734
+ if done is not None:
4735
+ return done
4736
+
4737
+ def one_fold(k):
4738
+ lo, hi = bounds[k], bounds[k + 1]
4739
+ Xf, Yf = X[lo:hi], Y[lo:hi]
4740
+ m = CovMultiTaskLasso(gram=(G - Xf.T @ Xf).ravel(),
4741
+ corr=C - Xf.T @ Yf,
4742
+ nobs=n - (hi - lo))
4743
+ path = m.fit_path(self.alphas_, tol=tol, l1_ratio=l1_ratio)
4744
+ # all validation residuals in one product: (nf, num, T)
4745
+ resid = np.tensordot(Xf, path, axes=([1], [1])) - Yf[:, None, :]
4746
+ self.mse_path_[:, k] = np.mean(resid * resid, axis=(0, 2))
4747
+
4748
+ if int(self.n_jobs) > 1:
4749
+ from concurrent.futures import ThreadPoolExecutor
4750
+ with ThreadPoolExecutor(max_workers=int(self.n_jobs)) as ex:
4751
+ list(ex.map(one_fold, range(cv)))
4752
+ else:
4753
+ for k in range(cv):
4754
+ one_fold(k)
4755
+ return self._finish(full)
4756
+
4757
+ def _fit_gpu(self, X, Y, full, G, C, bounds, n):
4758
+ # The grid as one launch, the fold's Gram shared by its
4759
+ # problems and nobs absorbed into each problem's lambda as in
4760
+ # CovLassoCV; None when the device declined.
4761
+ p_, T = full.p, full.n_tasks
4762
+ num, cv = int(self.num), int(self.cv)
4763
+ grams = np.empty((cv, p_ * p_))
4764
+ corrs = np.empty((cv, p_ * T))
4765
+ nobs_k = np.empty(cv)
4766
+ for k in range(cv):
4767
+ lo, hi = bounds[k], bounds[k + 1]
4768
+ Xf, Yf = X[lo:hi], Y[lo:hi]
4769
+ grams[k] = (G - Xf.T @ Xf).ravel()
4770
+ corrs[k] = (C - Xf.T @ Yf).ravel()
4771
+ nobs_k[k] = n - (hi - lo)
4772
+ lams = np.tile(self.alphas_, cv) * np.repeat(nobs_k, num)
4773
+ W = _grid_descend(grams, corrs, lams, p_, T, tol=float(self.tol),
4774
+ l1_ratio=float(self.l1_ratio))
4775
+ if W is None:
4776
+ return None
4777
+ W = W.reshape(cv, num, p_, T)
4778
+ for k in range(cv):
4779
+ lo, hi = bounds[k], bounds[k + 1]
4780
+ resid = (np.tensordot(X[lo:hi], W[k], axes=([1], [1]))
4781
+ - Y[lo:hi, None, :])
4782
+ self.mse_path_[:, k] = np.mean(resid * resid, axis=(0, 2))
4783
+ return self._finish(full)
4784
+
4785
+ def _finish(self, full):
4786
+ mean = self.mse_path_.mean(axis=1)
4787
+ self.alpha_ = float(self.alphas_[int(np.argmin(mean))])
4788
+ self.coef_ = full.fit(self.alpha_, tol=float(self.tol),
4789
+ l1_ratio=float(self.l1_ratio))
4790
+ self.intercept_ = 0.0 if self.coef_.ndim == 1 else np.zeros(self.coef_.shape[1])
4791
+ return self
4792
+
4793
+ def predict(self, X):
4794
+ return pred_x(self, X) @ self.coef_