CERM 1.0.0a1__py3-none-any.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 (74) hide show
  1. cerm/__init__.py +117 -0
  2. cerm/_compat/__init__.py +19 -0
  3. cerm/_compat/sklearn.py +441 -0
  4. cerm/_experimental_undr_geometry.py +431 -0
  5. cerm/_internal/__init__.py +1 -0
  6. cerm/_internal/cerm_embedding_graph_fusion.py +222 -0
  7. cerm/_internal/cerm_embedding_native_codegen.py +103 -0
  8. cerm/_internal/cerm_fused_regression.py +1406 -0
  9. cerm/_internal/cerm_fused_regression_contracts.py +321 -0
  10. cerm/_internal/cerm_fused_regression_native_codegen.py +195 -0
  11. cerm/_internal/cerm_fused_regression_semantic.py +965 -0
  12. cerm/_internal/cerm_graph_autotune_v2.py +180 -0
  13. cerm/_internal/cerm_graph_int16_codegen.py +243 -0
  14. cerm/_internal/cerm_graph_native_codegen.py +210 -0
  15. cerm/_internal/cerm_graph_native_codegen_v2.py +304 -0
  16. cerm/_internal/cerm_graph_optimizer.py +932 -0
  17. cerm/_internal/cerm_graph_optimizer_v2.py +771 -0
  18. cerm/_internal/cerm_graph_quantization.py +366 -0
  19. cerm/_internal/cerm_hierarchical_residual.py +551 -0
  20. cerm/_internal/cerm_hierarchical_residual_legacy.py +1818 -0
  21. cerm/_internal/cerm_hybrid_native_codegen.py +117 -0
  22. cerm/_internal/cerm_hybrid_quotient_block.py +1231 -0
  23. cerm/_internal/cerm_multioutput_subspace.py +552 -0
  24. cerm/_internal/cerm_native_build.py +67 -0
  25. cerm/_internal/cerm_nested_representation.py +287 -0
  26. cerm/_internal/cerm_quotient_block.py +583 -0
  27. cerm/_internal/cerm_regression_native_codegen.py +210 -0
  28. cerm/_internal/cerm_shared_native_codegen.py +351 -0
  29. cerm/_internal/cerm_shared_statistics.py +825 -0
  30. cerm/_internal/cerm_stable_quotient_block.py +528 -0
  31. cerm/_internal/cerm_state_design.py +103 -0
  32. cerm/_internal/cerm_training_core_runtime.py +1087 -0
  33. cerm/_internal/cerm_typed_quotient_adapters_v4.py +1229 -0
  34. cerm/_internal/cerm_weighted_representation.py +456 -0
  35. cerm/_internal/native/cerm_training_core.cpp +1577 -0
  36. cerm/_show_versions.py +32 -0
  37. cerm/_version.py +1 -0
  38. cerm/adapters.py +13 -0
  39. cerm/adaptive_representation.py +291 -0
  40. cerm/calibration.py +230 -0
  41. cerm/compiler.py +3 -0
  42. cerm/config.py +81 -0
  43. cerm/default_regression.py +34 -0
  44. cerm/diagnostics.py +167 -0
  45. cerm/errors.py +67 -0
  46. cerm/estimator.py +1504 -0
  47. cerm/experimental_undr_v21.py +2154 -0
  48. cerm/fused_regression.py +301 -0
  49. cerm/generalized_regression.py +801 -0
  50. cerm/inspection.py +331 -0
  51. cerm/io.py +172 -0
  52. cerm/multioutput.py +380 -0
  53. cerm/multioutput_regression.py +578 -0
  54. cerm/native_runtime.py +97 -0
  55. cerm/objectives.py +381 -0
  56. cerm/params.py +431 -0
  57. cerm/portable.py +303 -0
  58. cerm/program.py +1153 -0
  59. cerm/regression.py +2755 -0
  60. cerm/resources.py +331 -0
  61. cerm/search.py +472 -0
  62. cerm/selection.py +209 -0
  63. cerm/shared_multitask.py +2057 -0
  64. cerm/training_cache.py +482 -0
  65. cerm/training_graph.py +888 -0
  66. cerm/validation.py +318 -0
  67. cerm-1.0.0a1.dist-info/METADATA +256 -0
  68. cerm-1.0.0a1.dist-info/RECORD +74 -0
  69. cerm-1.0.0a1.dist-info/WHEEL +5 -0
  70. cerm-1.0.0a1.dist-info/licenses/LICENSE +201 -0
  71. cerm-1.0.0a1.dist-info/licenses/LICENSES/LIBLINEAR-BSD-3-Clause.txt +29 -0
  72. cerm-1.0.0a1.dist-info/licenses/LICENSES/SCIKIT-LEARN-BSD-3-Clause.txt +29 -0
  73. cerm-1.0.0a1.dist-info/licenses/THIRD_PARTY_NOTICES.md +26 -0
  74. cerm-1.0.0a1.dist-info/top_level.txt +1 -0
cerm/__init__.py ADDED
@@ -0,0 +1,117 @@
1
+ from ._version import __version__
2
+ from ._show_versions import show_versions
3
+ from .config import CERMConfig, TypedAdapterConfig
4
+ from .diagnostics import FitDiagnostics
5
+ from .inspection import (
6
+ CERMModelInspection,
7
+ CERMModelSummary,
8
+ feature_table,
9
+ inspect_model,
10
+ interaction_table,
11
+ model_summary,
12
+ structure_table,
13
+ )
14
+ from .calibration import CalibrationResult
15
+ from .training_cache import NewtonHistogramCache
16
+ from .errors import (
17
+ CERMAliasConflictError,
18
+ CERMDataSchemaError,
19
+ CERMParameterError,
20
+ CERMResourceLimitError,
21
+ CERMResourceWarning,
22
+ CERMValidationError,
23
+ )
24
+ from .resources import FitResourcePlan
25
+ from .estimator import CERMClassifier
26
+ from .regression import (
27
+ CompiledRegressionProgram,
28
+ PortableRegressionAdapter,
29
+ PortableRegressionProgram,
30
+ RegressionSemanticProgram,
31
+ )
32
+ from .fused_regression import (
33
+ CERMFusedRegressor,
34
+ CompiledFusedRegressionProgram,
35
+ PortableFusedRegressionProgram,
36
+ )
37
+ from .default_regression import CERMRegressor, CERMRidgeRegressor
38
+ from .generalized_regression import CERMGeneralizedRegressor
39
+ from .multioutput import CERMMultiLabelClassifier
40
+ from .multioutput_regression import CERMMultiOutputRegressor
41
+ from .params import (
42
+ ResolvedCERMParams,
43
+ get_tunable_params,
44
+ get_search_params,
45
+ get_resource_params,
46
+ get_convenience_params,
47
+ )
48
+ from .search import CERMSearchCV, SearchDiagnostics
49
+ from .io import verify_export
50
+ from .portable import PortableTypedAdapter
51
+ from .shared_multitask import (
52
+ CompiledSharedFiniteStateProgram,
53
+ SharedFiniteStateProgram,
54
+ )
55
+ from .program import (
56
+ CompiledProgram,
57
+ CompiledProgramBundle,
58
+ ConstantBinaryProgram,
59
+ OptimizedProgram,
60
+ ProgramBundle,
61
+ SemanticProgram,
62
+ )
63
+
64
+
65
+ __all__ = [
66
+ "__version__",
67
+ "show_versions",
68
+ "CERMClassifier",
69
+ "CERMRegressor",
70
+ "CERMFusedRegressor",
71
+ "CERMRidgeRegressor",
72
+ "CERMGeneralizedRegressor",
73
+ "CERMMultiLabelClassifier",
74
+ "CERMMultiOutputRegressor",
75
+ "ResolvedCERMParams",
76
+ "get_tunable_params",
77
+ "get_search_params",
78
+ "get_resource_params",
79
+ "get_convenience_params",
80
+ "CERMSearchCV",
81
+ "SearchDiagnostics",
82
+ "CERMConfig",
83
+ "TypedAdapterConfig",
84
+ "SemanticProgram",
85
+ "RegressionSemanticProgram",
86
+ "CompiledRegressionProgram",
87
+ "PortableRegressionAdapter",
88
+ "PortableRegressionProgram",
89
+ "PortableFusedRegressionProgram",
90
+ "CompiledFusedRegressionProgram",
91
+ "ProgramBundle",
92
+ "CompiledProgramBundle",
93
+ "ConstantBinaryProgram",
94
+ "OptimizedProgram",
95
+ "CompiledProgram",
96
+ "FitDiagnostics",
97
+ "CERMModelSummary",
98
+ "CERMModelInspection",
99
+ "model_summary",
100
+ "inspect_model",
101
+ "feature_table",
102
+ "interaction_table",
103
+ "structure_table",
104
+ "CalibrationResult",
105
+ "NewtonHistogramCache",
106
+ "FitResourcePlan",
107
+ "CERMValidationError",
108
+ "CERMDataSchemaError",
109
+ "CERMParameterError",
110
+ "CERMAliasConflictError",
111
+ "CERMResourceWarning",
112
+ "CERMResourceLimitError",
113
+ "verify_export",
114
+ "PortableTypedAdapter",
115
+ "SharedFiniteStateProgram",
116
+ "CompiledSharedFiniteStateProgram",
117
+ ]
@@ -0,0 +1,19 @@
1
+ """Compatibility helpers for optional or version-sensitive dependencies.
2
+
3
+ Private dependency APIs must be imported only from modules in this package.
4
+ The rest of CERM should use the stable wrappers exposed here.
5
+ """
6
+
7
+ from .sklearn import (
8
+ fit_ridge_lsqr_alpha_path_exact,
9
+ num_samples,
10
+ safe_indexing,
11
+ train_binary_liblinear,
12
+ )
13
+
14
+ __all__ = [
15
+ "fit_ridge_lsqr_alpha_path_exact",
16
+ "num_samples",
17
+ "safe_indexing",
18
+ "train_binary_liblinear",
19
+ ]
@@ -0,0 +1,441 @@
1
+ """Small compatibility boundary for scikit-learn integration.
2
+
3
+ CERM primarily uses public scikit-learn APIs. The optional optimized
4
+ LIBLINEAR path necessarily touches a private extension module; that access is
5
+ isolated here and callers must retain a public-estimator fallback.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from concurrent.futures import ThreadPoolExecutor
11
+ from typing import Any
12
+
13
+ import numpy as np
14
+ from joblib import effective_n_jobs
15
+ from scipy import sparse
16
+
17
+ from .._internal.cerm_training_core_runtime import (
18
+ TrainingCoreUnavailable,
19
+ _prebuilt_library_path,
20
+ load_native_training_core,
21
+ )
22
+
23
+
24
+ _NATIVE_LOGISTIC_SOURCE_BUILD_NNZ = 1_000_000
25
+
26
+
27
+ class PrivateSklearnAPIUnavailable(RuntimeError):
28
+ """Raised when an optional private scikit-learn fast path is unavailable."""
29
+
30
+
31
+ def num_samples(value: Any) -> int:
32
+ """Return the number of samples without relying on sklearn private helpers."""
33
+
34
+ if isinstance(value, (str, bytes)):
35
+ raise TypeError("Expected a collection or array-like object")
36
+ shape = getattr(value, "shape", None)
37
+ if shape is not None:
38
+ if len(shape) == 0:
39
+ raise TypeError("CERM requires an input with a sample dimension")
40
+ first = shape[0]
41
+ if isinstance(first, (int, np.integer)):
42
+ return int(first)
43
+ if hasattr(value, "__array__"):
44
+ array = np.asarray(value)
45
+ if array.ndim == 0:
46
+ raise TypeError("CERM requires an input with a sample dimension")
47
+ return int(array.shape[0])
48
+ try:
49
+ return int(len(value))
50
+ except TypeError as exc:
51
+ raise TypeError("Expected a collection or array-like object") from exc
52
+
53
+
54
+ def safe_indexing(value: Any, indices: Any) -> Any:
55
+ """Select rows from pandas, sparse, NumPy, or sequence inputs.
56
+
57
+ Only the integer/boolean row-indexing modes used by CERM cross-validation
58
+ are supported. This intentionally avoids sklearn's private
59
+ ``_safe_indexing`` API.
60
+ """
61
+
62
+ if hasattr(value, "iloc"):
63
+ return value.iloc[indices]
64
+ if sparse.issparse(value):
65
+ return value[indices]
66
+ if isinstance(value, np.ndarray):
67
+ return value[indices]
68
+ try:
69
+ array = np.asarray(value)
70
+ return array[indices]
71
+ except (TypeError, ValueError, IndexError) as exc:
72
+ raise TypeError("value does not support row indexing") from exc
73
+
74
+
75
+ def _native_training_core_ready_without_compile() -> bool:
76
+ if load_native_training_core.cache_info().currsize:
77
+ return True
78
+ prebuilt = _prebuilt_library_path()
79
+ return bool(prebuilt is not None and prebuilt.is_file())
80
+
81
+
82
+ def train_binary_liblinear(
83
+ design: Any,
84
+ target: np.ndarray,
85
+ *,
86
+ C: float,
87
+ seed: int,
88
+ max_iter: int,
89
+ sample_weight: np.ndarray | None = None,
90
+ ) -> tuple[np.ndarray, np.ndarray]:
91
+ """Solve the exact binary LIBLINEAR problem, preferring CERM's CSR-native path.
92
+
93
+ Packaged or already-loaded native cores are used for sparse designs without
94
+ a workload threshold. When a source compile would be required, CERM waits
95
+ until a sufficiently large CSR workload to amortize that one-time cost.
96
+
97
+ Returns
98
+ -------
99
+ raw_coef, n_iter
100
+ Outputs from the exact native solver or the private sklearn extension.
101
+ The caller retains a public ``LogisticRegression`` fallback.
102
+ """
103
+
104
+ if sparse.issparse(design):
105
+ native_ready = _native_training_core_ready_without_compile()
106
+ large_enough_to_compile = int(getattr(design, "nnz", 0)) >= _NATIVE_LOGISTIC_SOURCE_BUILD_NNZ
107
+ if native_ready or large_enough_to_compile:
108
+ try:
109
+ return load_native_training_core().binary_logistic_csr(
110
+ design,
111
+ target,
112
+ C=float(C),
113
+ seed=int(seed),
114
+ max_iter=int(max_iter),
115
+ sample_weight=sample_weight,
116
+ )
117
+ except (
118
+ TrainingCoreUnavailable,
119
+ AttributeError,
120
+ ImportError,
121
+ TypeError,
122
+ ValueError,
123
+ OverflowError,
124
+ OSError,
125
+ ):
126
+ pass
127
+
128
+ try:
129
+ from sklearn.svm import _liblinear
130
+ except (ImportError, AttributeError) as exc: # pragma: no cover - version dependent
131
+ raise PrivateSklearnAPIUnavailable(
132
+ "scikit-learn's private LIBLINEAR extension is unavailable"
133
+ ) from exc
134
+
135
+ _liblinear.set_verbosity_wrap(0)
136
+ is_sparse = bool(sparse.issparse(design))
137
+ class_weight = np.ones(2, dtype=np.float64)
138
+ if sample_weight is None:
139
+ sample_weight_array = np.ones(int(design.shape[0]), dtype=np.float64)
140
+ else:
141
+ sample_weight_array = np.asarray(sample_weight, dtype=np.float64).reshape(-1)
142
+ if len(sample_weight_array) != int(design.shape[0]):
143
+ raise ValueError("sample_weight length mismatch")
144
+ try:
145
+ return _liblinear.train_wrap(
146
+ design,
147
+ target,
148
+ is_sparse,
149
+ 0, # L2-regularized logistic regression, primal
150
+ 1e-4,
151
+ 1.0,
152
+ float(C),
153
+ class_weight,
154
+ int(max_iter),
155
+ int(seed),
156
+ 0.1,
157
+ sample_weight_array,
158
+ )
159
+ except (AttributeError, TypeError, ValueError, OverflowError) as exc:
160
+ raise PrivateSklearnAPIUnavailable(
161
+ "scikit-learn's private LIBLINEAR ABI is incompatible"
162
+ ) from exc
163
+
164
+
165
+ def fit_ridge_lsqr_alpha_path_exact(
166
+ design: Any,
167
+ target: np.ndarray,
168
+ alphas: np.ndarray,
169
+ *,
170
+ sample_weight: np.ndarray | None = None,
171
+ tol: float = 1e-4,
172
+ max_iter: int | None = None,
173
+ n_jobs: int | None = 1,
174
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
175
+ """Fit an exact LSQR Ridge path while sharing invariant preprocessing.
176
+
177
+ This is an optional optimization for the repeated-alpha validation path.
178
+ Each LSQR solve receives the same centered/rescaled matrix, right-hand side,
179
+ damping value and stopping criteria as an independent
180
+ ``Ridge(solver="lsqr")`` fit. The sparse transpose used by the implicit
181
+ centering operator is materialized once instead of once per LSQR matvec.
182
+
183
+ If the version-sensitive sklearn helpers are unavailable, the function
184
+ falls back to independent public ``Ridge`` fits.
185
+ """
186
+
187
+ alpha_array = np.asarray(alphas, dtype=np.float64).reshape(-1)
188
+ y = np.asarray(target, dtype=np.float64).reshape(-1)
189
+ if alpha_array.size == 0:
190
+ return (
191
+ np.empty((0, int(design.shape[1])), dtype=np.float64),
192
+ np.empty(0, dtype=np.float64),
193
+ np.empty(0, dtype=np.int32),
194
+ )
195
+
196
+ try:
197
+ from scipy.sparse import linalg as sparse_linalg
198
+ from sklearn.linear_model._base import _preprocess_data, _rescale_data
199
+ from sklearn.utils.validation import _check_sample_weight
200
+ except (ImportError, AttributeError): # pragma: no cover - version dependent
201
+ from sklearn.linear_model import Ridge
202
+
203
+ models = [
204
+ Ridge(
205
+ alpha=float(alpha),
206
+ solver="lsqr",
207
+ tol=float(tol),
208
+ max_iter=max_iter,
209
+ ).fit(design, y, sample_weight=sample_weight)
210
+ for alpha in alpha_array
211
+ ]
212
+ return (
213
+ np.vstack([np.asarray(model.coef_, dtype=np.float64) for model in models]),
214
+ np.asarray([float(model.intercept_) for model in models], dtype=np.float64),
215
+ np.asarray(
216
+ [int(np.asarray(model.n_iter_).reshape(-1)[0]) for model in models],
217
+ dtype=np.int32,
218
+ ),
219
+ )
220
+
221
+ X = design
222
+ weights = (
223
+ None
224
+ if sample_weight is None
225
+ else _check_sample_weight(sample_weight, X, dtype=X.dtype)
226
+ )
227
+ # ``_preprocess_data`` is private and changed shape between sklearn
228
+ # releases. Older versions accept ``rescale_with_sw`` and return a
229
+ # sixth work-array; newer versions removed both. The exact path performs
230
+ # weighted rescaling explicitly below, so the newer five-value call is the
231
+ # same preprocessing contract.
232
+ try:
233
+ processed = _preprocess_data(
234
+ X,
235
+ y,
236
+ fit_intercept=True,
237
+ copy=True,
238
+ sample_weight=weights,
239
+ rescale_with_sw=False,
240
+ )
241
+ except TypeError as exc:
242
+ if "rescale_with_sw" not in str(exc):
243
+ raise
244
+ processed = _preprocess_data(
245
+ X,
246
+ y,
247
+ fit_intercept=True,
248
+ copy=True,
249
+ sample_weight=weights,
250
+ )
251
+ if len(processed) == 6:
252
+ X_processed, y_processed, X_offset, y_offset, X_scale, _ = processed
253
+ elif len(processed) == 5:
254
+ X_processed, y_processed, X_offset, y_offset, X_scale = processed
255
+ else: # pragma: no cover - defensive boundary for future sklearn changes
256
+ raise PrivateSklearnAPIUnavailable(
257
+ "unsupported sklearn _preprocess_data return shape"
258
+ )
259
+ if weights is None:
260
+ X_rescaled = X_processed
261
+ y_rescaled = y_processed
262
+ sample_weight_sqrt = np.ones(X.shape[0], dtype=X.dtype)
263
+ else:
264
+ X_rescaled, y_rescaled, sample_weight_sqrt = _rescale_data(
265
+ X_processed, y_processed, weights
266
+ )
267
+
268
+ offset_scale = X_offset / X_scale
269
+ transpose = X_rescaled.T
270
+
271
+ def matvec(vector):
272
+ return X_rescaled.dot(vector) - sample_weight_sqrt * vector.dot(offset_scale)
273
+
274
+ def rmatvec(vector):
275
+ return transpose.dot(vector) - offset_scale * vector.dot(sample_weight_sqrt)
276
+
277
+ operator = sparse_linalg.LinearOperator(
278
+ shape=X_rescaled.shape,
279
+ matvec=matvec,
280
+ rmatvec=rmatvec,
281
+ )
282
+ coefficients = np.empty(
283
+ (len(alpha_array), X_rescaled.shape[1]), dtype=X_rescaled.dtype
284
+ )
285
+ iterations = np.empty(len(alpha_array), dtype=np.int32)
286
+ sqrt_alpha = np.sqrt(alpha_array)
287
+
288
+ def solve_one(item):
289
+ index, damping = item
290
+ result = sparse_linalg.lsqr(
291
+ operator,
292
+ y_rescaled,
293
+ damp=float(damping),
294
+ atol=float(tol),
295
+ btol=float(tol),
296
+ iter_lim=max_iter,
297
+ )
298
+ return int(index), np.asarray(result[0]), int(result[2])
299
+
300
+ workers = min(max(1, effective_n_jobs(n_jobs)), len(sqrt_alpha))
301
+ items = list(enumerate(sqrt_alpha.tolist()))
302
+ if workers > 1 and len(items) > 1:
303
+ with ThreadPoolExecutor(max_workers=workers) as pool:
304
+ solved = list(pool.map(solve_one, items))
305
+ else:
306
+ solved = [solve_one(item) for item in items]
307
+ for index, coefficient, n_iter in solved:
308
+ coefficients[index] = coefficient
309
+ iterations[index] = n_iter
310
+
311
+ coefficients = coefficients / X_scale
312
+ # Compute each intercept separately. This preserves the one-dimensional
313
+ # dot-product reduction order used by independent Ridge fits.
314
+ intercepts = np.asarray(
315
+ [y_offset - X_offset @ coefficients[index] for index in range(len(alpha_array))],
316
+ dtype=np.float64,
317
+ )
318
+ return coefficients, intercepts, iterations
319
+
320
+
321
+
322
+ def fit_multi_target_ridge_lsqr_exact(
323
+ design: Any,
324
+ target: np.ndarray,
325
+ *,
326
+ alpha: float,
327
+ tol: float,
328
+ max_iter: int,
329
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
330
+ """Fit one multi-target Ridge LSQR problem with shared sparse invariants.
331
+
332
+ Private sklearn preprocessing is intentionally isolated in this compatibility
333
+ module. Dense designs and incompatible sklearn versions retain an exact
334
+ public-Ridge fallback.
335
+ """
336
+ from sklearn.linear_model import Ridge
337
+
338
+ values = np.asarray(target, dtype=np.float64)
339
+ if values.ndim == 1:
340
+ values = values[:, None]
341
+ if not sparse.issparse(design):
342
+ model = Ridge(
343
+ alpha=float(alpha),
344
+ fit_intercept=True,
345
+ solver="lsqr",
346
+ max_iter=int(max_iter),
347
+ tol=float(tol),
348
+ ).fit(design, values)
349
+ coefficients = np.asarray(model.coef_, dtype=np.float64)
350
+ if coefficients.ndim == 1:
351
+ coefficients = coefficients[None, :]
352
+ return (
353
+ coefficients,
354
+ np.asarray(model.intercept_, dtype=np.float64).reshape(-1),
355
+ np.asarray(model.n_iter_, dtype=np.int32).reshape(-1),
356
+ )
357
+
358
+ try:
359
+ from scipy.sparse import linalg as sparse_linalg
360
+ from sklearn.linear_model._base import _preprocess_data
361
+ except (ImportError, AttributeError): # pragma: no cover - version dependent
362
+ model = Ridge(
363
+ alpha=float(alpha),
364
+ fit_intercept=True,
365
+ solver="lsqr",
366
+ max_iter=int(max_iter),
367
+ tol=float(tol),
368
+ ).fit(design, values)
369
+ coefficients = np.asarray(model.coef_, dtype=np.float64)
370
+ if coefficients.ndim == 1:
371
+ coefficients = coefficients[None, :]
372
+ return (
373
+ coefficients,
374
+ np.asarray(model.intercept_, dtype=np.float64).reshape(-1),
375
+ np.asarray(model.n_iter_, dtype=np.int32).reshape(-1),
376
+ )
377
+
378
+ try:
379
+ processed = _preprocess_data(
380
+ design,
381
+ values,
382
+ fit_intercept=True,
383
+ copy=True,
384
+ sample_weight=None,
385
+ rescale_with_sw=False,
386
+ )
387
+ except TypeError as exc:
388
+ if "rescale_with_sw" not in str(exc):
389
+ raise
390
+ processed = _preprocess_data(
391
+ design,
392
+ values,
393
+ fit_intercept=True,
394
+ copy=True,
395
+ sample_weight=None,
396
+ )
397
+ if len(processed) == 6:
398
+ X_processed, y_processed, X_offset, y_offset, X_scale, _ = processed
399
+ elif len(processed) == 5:
400
+ X_processed, y_processed, X_offset, y_offset, X_scale = processed
401
+ else: # pragma: no cover - defensive boundary for future sklearn changes
402
+ raise PrivateSklearnAPIUnavailable(
403
+ "unsupported sklearn _preprocess_data return shape"
404
+ )
405
+
406
+ sample_weight_sqrt = np.ones(X_processed.shape[0], dtype=X_processed.dtype)
407
+ offset_scale = X_offset / X_scale
408
+ transpose = X_processed.T
409
+
410
+ def matvec(vector):
411
+ return X_processed.dot(vector) - sample_weight_sqrt * vector.dot(offset_scale)
412
+
413
+ def rmatvec(vector):
414
+ return transpose.dot(vector) - offset_scale * vector.dot(sample_weight_sqrt)
415
+
416
+ operator = sparse_linalg.LinearOperator(
417
+ shape=X_processed.shape,
418
+ matvec=matvec,
419
+ rmatvec=rmatvec,
420
+ )
421
+ coefficients = np.empty(
422
+ (y_processed.shape[1], X_processed.shape[1]), dtype=np.float64
423
+ )
424
+ iterations = np.empty(y_processed.shape[1], dtype=np.int32)
425
+ damping = float(np.sqrt(float(alpha)))
426
+ for output in range(y_processed.shape[1]):
427
+ result = sparse_linalg.lsqr(
428
+ operator,
429
+ y_processed[:, output],
430
+ damp=damping,
431
+ atol=float(tol),
432
+ btol=float(tol),
433
+ iter_lim=int(max_iter),
434
+ )
435
+ coefficients[output] = np.asarray(result[0])
436
+ iterations[output] = int(result[2])
437
+ coefficients = coefficients / X_scale
438
+ intercepts = (
439
+ np.asarray(y_offset, dtype=np.float64) - coefficients @ X_offset
440
+ )
441
+ return coefficients, intercepts, iterations