scikit-learn-intelex 2024.6.0__py312-none-manylinux1_x86_64.whl → 2024.7.0__py312-none-manylinux1_x86_64.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.

Potentially problematic release.


This version of scikit-learn-intelex might be problematic. Click here for more details.

Files changed (55) hide show
  1. {scikit_learn_intelex-2024.6.0.dist-info → scikit_learn_intelex-2024.7.0.dist-info}/METADATA +2 -2
  2. {scikit_learn_intelex-2024.6.0.dist-info → scikit_learn_intelex-2024.7.0.dist-info}/RECORD +55 -41
  3. sklearnex/_config.py +3 -15
  4. sklearnex/_device_offload.py +9 -168
  5. sklearnex/basic_statistics/basic_statistics.py +127 -1
  6. sklearnex/basic_statistics/tests/test_basic_statistics.py +251 -0
  7. sklearnex/basic_statistics/tests/test_incremental_basic_statistics.py +1 -1
  8. sklearnex/cluster/dbscan.py +0 -1
  9. sklearnex/cluster/k_means.py +8 -0
  10. sklearnex/cluster/tests/test_kmeans.py +15 -3
  11. sklearnex/covariance/incremental_covariance.py +64 -13
  12. sklearnex/covariance/tests/test_incremental_covariance.py +35 -0
  13. sklearnex/decomposition/pca.py +25 -1
  14. sklearnex/dispatcher.py +94 -0
  15. sklearnex/ensemble/_forest.py +8 -35
  16. sklearnex/ensemble/tests/test_forest.py +9 -12
  17. sklearnex/linear_model/coordinate_descent.py +13 -0
  18. sklearnex/linear_model/linear.py +2 -34
  19. sklearnex/linear_model/logistic_regression.py +79 -59
  20. sklearnex/linear_model/ridge.py +7 -0
  21. sklearnex/linear_model/tests/test_linear.py +28 -3
  22. sklearnex/linear_model/tests/test_logreg.py +45 -3
  23. sklearnex/manifold/t_sne.py +4 -0
  24. sklearnex/metrics/pairwise.py +5 -0
  25. sklearnex/metrics/ranking.py +3 -0
  26. sklearnex/model_selection/split.py +3 -0
  27. sklearnex/neighbors/_lof.py +9 -0
  28. sklearnex/neighbors/common.py +45 -1
  29. sklearnex/neighbors/knn_classification.py +1 -20
  30. sklearnex/neighbors/knn_regression.py +1 -20
  31. sklearnex/neighbors/knn_unsupervised.py +31 -7
  32. sklearnex/preview/__init__.py +1 -1
  33. sklearnex/preview/linear_model/__init__.py +19 -0
  34. sklearnex/preview/linear_model/ridge.py +419 -0
  35. sklearnex/preview/linear_model/tests/test_ridge.py +102 -0
  36. sklearnex/spmd/basic_statistics/tests/test_basic_statistics_spmd.py +107 -0
  37. sklearnex/spmd/cluster/tests/test_dbscan_spmd.py +97 -0
  38. sklearnex/spmd/cluster/tests/test_kmeans_spmd.py +172 -0
  39. sklearnex/spmd/covariance/tests/test_covariance_spmd.py +107 -0
  40. sklearnex/spmd/decomposition/tests/test_pca_spmd.py +128 -0
  41. sklearnex/spmd/ensemble/tests/test_forest_spmd.py +265 -0
  42. sklearnex/spmd/linear_model/tests/test_linear_regression_spmd.py +145 -0
  43. sklearnex/spmd/linear_model/tests/test_logistic_regression_spmd.py +163 -0
  44. sklearnex/spmd/neighbors/tests/test_neighbors_spmd.py +288 -0
  45. sklearnex/svm/_common.py +19 -21
  46. sklearnex/svm/tests/test_svm.py +12 -20
  47. sklearnex/tests/_utils.py +143 -20
  48. sklearnex/tests/_utils_spmd.py +185 -0
  49. sklearnex/tests/test_config.py +4 -0
  50. sklearnex/tests/test_monkeypatch.py +12 -4
  51. sklearnex/tests/test_patching.py +16 -13
  52. sklearnex/tests/test_run_to_run_stability.py +21 -9
  53. {scikit_learn_intelex-2024.6.0.dist-info → scikit_learn_intelex-2024.7.0.dist-info}/LICENSE.txt +0 -0
  54. {scikit_learn_intelex-2024.6.0.dist-info → scikit_learn_intelex-2024.7.0.dist-info}/WHEEL +0 -0
  55. {scikit_learn_intelex-2024.6.0.dist-info → scikit_learn_intelex-2024.7.0.dist-info}/top_level.txt +0 -0
@@ -19,14 +19,16 @@ import warnings
19
19
  import numpy as np
20
20
  from scipy import sparse as sp
21
21
  from sklearn.neighbors._ball_tree import BallTree
22
- from sklearn.neighbors._base import VALID_METRICS
22
+ from sklearn.neighbors._base import VALID_METRICS, KNeighborsMixin
23
23
  from sklearn.neighbors._base import NeighborsBase as sklearn_NeighborsBase
24
24
  from sklearn.neighbors._kd_tree import KDTree
25
+ from sklearn.utils.validation import check_is_fitted
25
26
 
26
27
  from daal4py.sklearn._utils import sklearn_check_version
27
28
  from onedal.utils import _check_array, _num_features, _num_samples
28
29
 
29
30
  from .._utils import PatchingConditionsChain
31
+ from ..utils import get_namespace
30
32
 
31
33
 
32
34
  class KNeighborsDispatchingBase:
@@ -147,6 +149,10 @@ class KNeighborsDispatchingBase:
147
149
  patching_status = PatchingConditionsChain(
148
150
  f"sklearn.neighbors.{class_name}.{method_name}"
149
151
  )
152
+ if not patching_status.and_condition(
153
+ "radius" not in method_name, "RadiusNeighbors not implemented in sklearnex"
154
+ ):
155
+ return patching_status
150
156
 
151
157
  if not patching_status.and_condition(
152
158
  not isinstance(data[0], (KDTree, BallTree, sklearn_NeighborsBase)),
@@ -264,3 +270,41 @@ class KNeighborsDispatchingBase:
264
270
 
265
271
  def _onedal_cpu_supported(self, method_name, *data):
266
272
  return self._onedal_supported("cpu", method_name, *data)
273
+
274
+ def kneighbors_graph(self, X=None, n_neighbors=None, mode="connectivity"):
275
+ check_is_fitted(self)
276
+ if n_neighbors is None:
277
+ n_neighbors = self.n_neighbors
278
+
279
+ # check the input only in self.kneighbors
280
+
281
+ # construct CSR matrix representation of the k-NN graph
282
+ if mode == "connectivity":
283
+ A_ind = self.kneighbors(X, n_neighbors, return_distance=False)
284
+ xp, _ = get_namespace(A_ind)
285
+ n_queries = A_ind.shape[0]
286
+ A_data = xp.ones(n_queries * n_neighbors)
287
+
288
+ elif mode == "distance":
289
+ A_data, A_ind = self.kneighbors(X, n_neighbors, return_distance=True)
290
+ xp, _ = get_namespace(A_ind)
291
+ A_data = xp.reshape(A_data, (-1,))
292
+
293
+ else:
294
+ raise ValueError(
295
+ 'Unsupported mode, must be one of "connectivity", '
296
+ f'or "distance" but got "{mode}" instead'
297
+ )
298
+
299
+ n_queries = A_ind.shape[0]
300
+ n_samples_fit = self.n_samples_fit_
301
+ n_nonzero = n_queries * n_neighbors
302
+ A_indptr = xp.arange(0, n_nonzero + 1, n_neighbors)
303
+
304
+ kneighbors_graph = sp.csr_matrix(
305
+ (A_data, xp.reshape(A_ind, (-1,)), A_indptr), shape=(n_queries, n_samples_fit)
306
+ )
307
+
308
+ return kneighbors_graph
309
+
310
+ kneighbors_graph.__doc__ = KNeighborsMixin.kneighbors_graph.__doc__
@@ -32,7 +32,7 @@ from .common import KNeighborsDispatchingBase
32
32
  @control_n_jobs(
33
33
  decorated_methods=["fit", "predict", "predict_proba", "kneighbors", "score"]
34
34
  )
35
- class KNeighborsClassifier(sklearn_KNeighborsClassifier, KNeighborsDispatchingBase):
35
+ class KNeighborsClassifier(KNeighborsDispatchingBase, sklearn_KNeighborsClassifier):
36
36
  __doc__ = sklearn_KNeighborsClassifier.__doc__
37
37
  if sklearn_check_version("1.2"):
38
38
  _parameter_constraints: dict = {
@@ -169,24 +169,6 @@ class KNeighborsClassifier(sklearn_KNeighborsClassifier, KNeighborsDispatchingBa
169
169
  return_distance=return_distance,
170
170
  )
171
171
 
172
- @wrap_output_data
173
- def radius_neighbors(
174
- self, X=None, radius=None, return_distance=True, sort_results=False
175
- ):
176
- _onedal_estimator = getattr(self, "_onedal_estimator", None)
177
-
178
- if (
179
- _onedal_estimator is not None
180
- or getattr(self, "_tree", 0) is None
181
- and self._fit_method == "kd_tree"
182
- ):
183
- sklearn_NearestNeighbors.fit(self, self._fit_X, getattr(self, "_y", None))
184
- result = sklearn_NearestNeighbors.radius_neighbors(
185
- self, X, radius, return_distance, sort_results
186
- )
187
-
188
- return result
189
-
190
172
  def _onedal_fit(self, X, y, queue=None):
191
173
  onedal_params = {
192
174
  "n_neighbors": self.n_neighbors,
@@ -242,4 +224,3 @@ class KNeighborsClassifier(sklearn_KNeighborsClassifier, KNeighborsDispatchingBa
242
224
  predict_proba.__doc__ = sklearn_KNeighborsClassifier.predict_proba.__doc__
243
225
  score.__doc__ = sklearn_KNeighborsClassifier.score.__doc__
244
226
  kneighbors.__doc__ = sklearn_KNeighborsClassifier.kneighbors.__doc__
245
- radius_neighbors.__doc__ = sklearn_NearestNeighbors.radius_neighbors.__doc__
@@ -30,7 +30,7 @@ from .common import KNeighborsDispatchingBase
30
30
 
31
31
 
32
32
  @control_n_jobs(decorated_methods=["fit", "predict", "kneighbors"])
33
- class KNeighborsRegressor(sklearn_KNeighborsRegressor, KNeighborsDispatchingBase):
33
+ class KNeighborsRegressor(KNeighborsDispatchingBase, sklearn_KNeighborsRegressor):
34
34
  __doc__ = sklearn_KNeighborsRegressor.__doc__
35
35
  if sklearn_check_version("1.2"):
36
36
  _parameter_constraints: dict = {
@@ -152,24 +152,6 @@ class KNeighborsRegressor(sklearn_KNeighborsRegressor, KNeighborsDispatchingBase
152
152
  return_distance=return_distance,
153
153
  )
154
154
 
155
- @wrap_output_data
156
- def radius_neighbors(
157
- self, X=None, radius=None, return_distance=True, sort_results=False
158
- ):
159
- _onedal_estimator = getattr(self, "_onedal_estimator", None)
160
-
161
- if (
162
- _onedal_estimator is not None
163
- or getattr(self, "_tree", 0) is None
164
- and self._fit_method == "kd_tree"
165
- ):
166
- sklearn_NearestNeighbors.fit(self, self._fit_X, getattr(self, "_y", None))
167
- result = sklearn_NearestNeighbors.radius_neighbors(
168
- self, X, radius, return_distance, sort_results
169
- )
170
-
171
- return result
172
-
173
155
  def _onedal_fit(self, X, y, queue=None):
174
156
  onedal_params = {
175
157
  "n_neighbors": self.n_neighbors,
@@ -218,5 +200,4 @@ class KNeighborsRegressor(sklearn_KNeighborsRegressor, KNeighborsDispatchingBase
218
200
  fit.__doc__ = sklearn_KNeighborsRegressor.__doc__
219
201
  predict.__doc__ = sklearn_KNeighborsRegressor.predict.__doc__
220
202
  kneighbors.__doc__ = sklearn_KNeighborsRegressor.kneighbors.__doc__
221
- radius_neighbors.__doc__ = sklearn_NearestNeighbors.radius_neighbors.__doc__
222
203
  score.__doc__ = sklearn_KNeighborsRegressor.score.__doc__
@@ -26,7 +26,7 @@ from .common import KNeighborsDispatchingBase
26
26
 
27
27
 
28
28
  @control_n_jobs(decorated_methods=["fit", "kneighbors"])
29
- class NearestNeighbors(sklearn_NearestNeighbors, KNeighborsDispatchingBase):
29
+ class NearestNeighbors(KNeighborsDispatchingBase, sklearn_NearestNeighbors):
30
30
  __doc__ = sklearn_NearestNeighbors.__doc__
31
31
  if sklearn_check_version("1.2"):
32
32
  _parameter_constraints: dict = {**sklearn_NearestNeighbors._parameter_constraints}
@@ -88,19 +88,40 @@ class NearestNeighbors(sklearn_NearestNeighbors, KNeighborsDispatchingBase):
88
88
  def radius_neighbors(
89
89
  self, X=None, radius=None, return_distance=True, sort_results=False
90
90
  ):
91
- _onedal_estimator = getattr(self, "_onedal_estimator", None)
92
-
93
91
  if (
94
- _onedal_estimator is not None
92
+ hasattr(self, "_onedal_estimator")
95
93
  or getattr(self, "_tree", 0) is None
96
94
  and self._fit_method == "kd_tree"
97
95
  ):
98
96
  sklearn_NearestNeighbors.fit(self, self._fit_X, getattr(self, "_y", None))
99
- result = sklearn_NearestNeighbors.radius_neighbors(
100
- self, X, radius, return_distance, sort_results
97
+ return dispatch(
98
+ self,
99
+ "radius_neighbors",
100
+ {
101
+ "onedal": None,
102
+ "sklearn": sklearn_NearestNeighbors.radius_neighbors,
103
+ },
104
+ X,
105
+ radius=radius,
106
+ return_distance=return_distance,
107
+ sort_results=sort_results,
101
108
  )
102
109
 
103
- return result
110
+ def radius_neighbors_graph(
111
+ self, X=None, radius=None, mode="connectivity", sort_results=False
112
+ ):
113
+ return dispatch(
114
+ self,
115
+ "radius_neighbors_graph",
116
+ {
117
+ "onedal": None,
118
+ "sklearn": sklearn_NearestNeighbors.radius_neighbors_graph,
119
+ },
120
+ X,
121
+ radius=radius,
122
+ mode=mode,
123
+ sort_results=sort_results,
124
+ )
104
125
 
105
126
  def _onedal_fit(self, X, y=None, queue=None):
106
127
  onedal_params = {
@@ -144,3 +165,6 @@ class NearestNeighbors(sklearn_NearestNeighbors, KNeighborsDispatchingBase):
144
165
  fit.__doc__ = sklearn_NearestNeighbors.__doc__
145
166
  kneighbors.__doc__ = sklearn_NearestNeighbors.kneighbors.__doc__
146
167
  radius_neighbors.__doc__ = sklearn_NearestNeighbors.radius_neighbors.__doc__
168
+ radius_neighbors_graph.__doc__ = (
169
+ sklearn_NearestNeighbors.radius_neighbors_graph.__doc__
170
+ )
@@ -14,4 +14,4 @@
14
14
  # limitations under the License.
15
15
  # ==============================================================================
16
16
 
17
- __all__ = ["cluster", "covariance", "decomposition"]
17
+ __all__ = ["cluster", "covariance", "decomposition", "linear_model"]
@@ -0,0 +1,19 @@
1
+ # ===============================================================================
2
+ # Copyright 2024 Intel Corporation
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ # ===============================================================================
16
+
17
+ from .ridge import Ridge
18
+
19
+ __all__ = ["Ridge"]
@@ -0,0 +1,419 @@
1
+ # ===============================================================================
2
+ # Copyright 2024 Intel Corporation
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ # ===============================================================================
16
+
17
+ import logging
18
+
19
+ from daal4py.sklearn._utils import daal_check_version, sklearn_check_version
20
+
21
+ if daal_check_version((2024, "P", 600)):
22
+ import numbers
23
+
24
+ import numpy as np
25
+ from scipy.sparse import issparse
26
+ from sklearn.linear_model import Ridge as sklearn_Ridge
27
+ from sklearn.metrics import r2_score
28
+ from sklearn.utils.validation import check_is_fitted, check_X_y
29
+
30
+ from daal4py.sklearn.linear_model._ridge import _fit_ridge as daal4py_fit_ridge
31
+
32
+ if sklearn_check_version("1.0") and not sklearn_check_version("1.2"):
33
+ from sklearn.linear_model._base import _deprecate_normalize
34
+ if sklearn_check_version("1.1") and not sklearn_check_version("1.2"):
35
+ from sklearn.utils import check_scalar
36
+
37
+ from onedal.linear_model import Ridge as onedal_Ridge
38
+ from onedal.utils import _num_features, _num_samples
39
+
40
+ from ..._device_offload import dispatch, wrap_output_data
41
+ from ..._utils import PatchingConditionsChain
42
+
43
+ def _is_numeric_scalar(value):
44
+ """
45
+ Determines if the provided value is a numeric scalar.
46
+
47
+ Args:
48
+ value: The value to be checked.
49
+
50
+ Returns:
51
+ bool: True if the value is a numeric scalar, False otherwise.
52
+ """
53
+ return isinstance(value, numbers.Real)
54
+
55
+ class Ridge(sklearn_Ridge):
56
+ __doc__ = sklearn_Ridge.__doc__
57
+
58
+ if sklearn_check_version("1.2"):
59
+ _parameter_constraints: dict = {**sklearn_Ridge._parameter_constraints}
60
+
61
+ def __init__(
62
+ self,
63
+ alpha=1.0,
64
+ fit_intercept=True,
65
+ copy_X=True,
66
+ max_iter=None,
67
+ tol=1e-4,
68
+ solver="auto",
69
+ positive=False,
70
+ random_state=None,
71
+ ):
72
+ super().__init__(
73
+ alpha=alpha,
74
+ fit_intercept=fit_intercept,
75
+ copy_X=copy_X,
76
+ max_iter=max_iter,
77
+ tol=tol,
78
+ solver=solver,
79
+ positive=positive,
80
+ random_state=random_state,
81
+ )
82
+
83
+ elif sklearn_check_version("1.0"):
84
+
85
+ def __init__(
86
+ self,
87
+ alpha=1.0,
88
+ fit_intercept=True,
89
+ normalize="deprecated",
90
+ copy_X=True,
91
+ max_iter=None,
92
+ tol=1e-3,
93
+ solver="auto",
94
+ positive=False,
95
+ random_state=None,
96
+ ):
97
+ super().__init__(
98
+ alpha=alpha,
99
+ fit_intercept=fit_intercept,
100
+ normalize=normalize,
101
+ copy_X=copy_X,
102
+ max_iter=max_iter,
103
+ solver=solver,
104
+ tol=tol,
105
+ positive=positive,
106
+ random_state=random_state,
107
+ )
108
+
109
+ else:
110
+
111
+ def __init__(
112
+ self,
113
+ alpha=1.0,
114
+ fit_intercept=True,
115
+ normalize=False,
116
+ copy_X=True,
117
+ max_iter=None,
118
+ tol=1e-3,
119
+ solver="auto",
120
+ random_state=None,
121
+ ):
122
+ super().__init__(
123
+ alpha=alpha,
124
+ fit_intercept=fit_intercept,
125
+ normalize=normalize,
126
+ copy_X=copy_X,
127
+ max_iter=max_iter,
128
+ tol=tol,
129
+ solver=solver,
130
+ random_state=random_state,
131
+ )
132
+
133
+ def fit(self, X, y, sample_weight=None):
134
+ # It is necessary to properly update coefs for predict if we
135
+ # fallback to sklearn in dispatch
136
+ if hasattr(self, "_onedal_estimator"):
137
+ del self._onedal_estimator
138
+
139
+ dispatch(
140
+ self,
141
+ "fit",
142
+ {
143
+ "onedal": self.__class__._onedal_fit,
144
+ "sklearn": sklearn_Ridge.fit,
145
+ },
146
+ X,
147
+ y,
148
+ sample_weight,
149
+ )
150
+ return self
151
+
152
+ @wrap_output_data
153
+ def predict(self, X):
154
+ check_is_fitted(self)
155
+
156
+ return dispatch(
157
+ self,
158
+ "predict",
159
+ {
160
+ "onedal": self.__class__._onedal_predict,
161
+ "sklearn": sklearn_Ridge.predict,
162
+ },
163
+ X,
164
+ )
165
+
166
+ @wrap_output_data
167
+ def score(self, X, y, sample_weight=None):
168
+ check_is_fitted(self)
169
+
170
+ return dispatch(
171
+ self,
172
+ "score",
173
+ {
174
+ "onedal": self.__class__._onedal_score,
175
+ "sklearn": sklearn_Ridge.score,
176
+ },
177
+ X,
178
+ y,
179
+ sample_weight=sample_weight,
180
+ )
181
+
182
+ def _onedal_fit_supported(self, patching_status, method_name, *data):
183
+ assert method_name == "fit"
184
+ assert len(data) == 3
185
+ X, y, sample_weight = data
186
+
187
+ normalize_is_set = (
188
+ hasattr(self, "normalize")
189
+ and self.normalize
190
+ and self.normalize != "deprecated"
191
+ )
192
+ positive_is_set = hasattr(self, "positive") and self.positive
193
+
194
+ n_samples = _num_samples(X)
195
+ n_features = _num_features(X, fallback_1d=True)
196
+
197
+ # Check if equations are well defined
198
+ is_underdetermined = n_samples < (n_features + int(self.fit_intercept))
199
+
200
+ patching_status.and_conditions(
201
+ [
202
+ (
203
+ self.solver == "auto",
204
+ f"'{self.solver}' solver is not supported. "
205
+ "Only 'auto' solver is supported.",
206
+ ),
207
+ (
208
+ not issparse(X) and not issparse(y),
209
+ "Sparse input is not supported.",
210
+ ),
211
+ (
212
+ not is_underdetermined,
213
+ "The shape of X (fitting) does not satisfy oneDAL requirements:"
214
+ "Number of features + 1 >= number of samples.",
215
+ ),
216
+ (sample_weight is None, "Sample weight is not supported."),
217
+ (not normalize_is_set, "Normalization is not supported."),
218
+ (
219
+ not positive_is_set,
220
+ "Forced positive coefficients are not supported.",
221
+ ),
222
+ ]
223
+ )
224
+
225
+ return patching_status
226
+
227
+ def _onedal_predict_supported(self, patching_status, method_name, *data):
228
+ assert method_name in ["predict", "score"]
229
+ assert len(data) <= 2
230
+
231
+ n_samples = _num_samples(data[0])
232
+ model_is_sparse = issparse(self.coef_) or (
233
+ self.fit_intercept and issparse(self.intercept_)
234
+ )
235
+ patching_status.and_conditions(
236
+ [
237
+ (
238
+ self.solver == "auto",
239
+ f"'{self.solver}' solver is not supported. "
240
+ "Only 'auto' solver is supported.",
241
+ ),
242
+ (n_samples > 0, "Number of samples is less than 1."),
243
+ (not issparse(data[0]), "Sparse input is not supported."),
244
+ (not model_is_sparse, "Sparse coefficients are not supported."),
245
+ ]
246
+ )
247
+
248
+ return patching_status
249
+
250
+ def _onedal_gpu_supported(self, method_name, *data):
251
+ patching_status = PatchingConditionsChain(
252
+ f"sklearn.linear_model.{self.__class__.__name__}.fit"
253
+ )
254
+
255
+ if method_name == "fit":
256
+ patching_status.and_condition(
257
+ _is_numeric_scalar(self.alpha),
258
+ "Non-scalar alpha is not supported for GPU.",
259
+ )
260
+
261
+ return self._onedal_fit_supported(patching_status, method_name, *data)
262
+
263
+ if method_name in ["predict", "score"]:
264
+ return self._onedal_predict_supported(patching_status, method_name, *data)
265
+
266
+ raise RuntimeError(
267
+ f"Unknown method {method_name} in {self.__class__.__name__}"
268
+ )
269
+
270
+ def _onedal_cpu_supported(self, method_name, *data):
271
+ patching_status = PatchingConditionsChain(
272
+ f"sklearn.linear_model.{self.__class__.__name__}.fit"
273
+ )
274
+
275
+ if method_name == "fit":
276
+ return self._onedal_fit_supported(patching_status, method_name, *data)
277
+
278
+ if method_name in ["predict", "score"]:
279
+ return self._onedal_predict_supported(patching_status, method_name, *data)
280
+
281
+ raise RuntimeError(
282
+ f"Unknown method {method_name} in {self.__class__.__name__}"
283
+ )
284
+
285
+ def _initialize_onedal_estimator(self):
286
+ onedal_params = {
287
+ "fit_intercept": self.fit_intercept,
288
+ "alpha": self.alpha,
289
+ "copy_X": self.copy_X,
290
+ }
291
+ self._onedal_estimator = onedal_Ridge(**onedal_params)
292
+
293
+ def _daal_fit(self, X, y, sample_weight=None):
294
+ daal4py_fit_ridge(self, X, y, sample_weight)
295
+ self._onedal_estimator.n_features_in_ = _num_features(X, fallback_1d=True)
296
+ self._onedal_estimator.coef_ = self.coef_
297
+ self._onedal_estimator.intercept_ = self.intercept_
298
+
299
+ def _onedal_fit(self, X, y, sample_weight, queue=None):
300
+ # `Sample weight` is not supported. Expected to be None value.
301
+ assert sample_weight is None
302
+
303
+ if sklearn_check_version("1.2"):
304
+ self._validate_params()
305
+ elif sklearn_check_version("1.1"):
306
+ if self.max_iter is not None:
307
+ self.max_iter = check_scalar(
308
+ self.max_iter, "max_iter", target_type=numbers.Integral, min_val=1
309
+ )
310
+ self.tol = check_scalar(
311
+ self.tol, "tol", target_type=numbers.Real, min_val=0.0
312
+ )
313
+ if self.alpha is not None and not isinstance(
314
+ self.alpha, (np.ndarray, tuple)
315
+ ):
316
+ self.alpha = check_scalar(
317
+ self.alpha,
318
+ "alpha",
319
+ target_type=numbers.Real,
320
+ min_val=0.0,
321
+ include_boundaries="left",
322
+ )
323
+
324
+ check_params = {
325
+ "X": X,
326
+ "y": y,
327
+ "dtype": [np.float64, np.float32],
328
+ "accept_sparse": ["csr", "csc", "coo"],
329
+ "y_numeric": True,
330
+ "multi_output": True,
331
+ }
332
+ if sklearn_check_version("1.0"):
333
+ X, y = self._validate_data(**check_params)
334
+ else:
335
+ X, y = check_X_y(**check_params)
336
+
337
+ if sklearn_check_version("1.0") and not sklearn_check_version("1.2"):
338
+ self._normalize = _deprecate_normalize(
339
+ self.normalize,
340
+ default=False,
341
+ estimator_name=self.__class__.__name__,
342
+ )
343
+
344
+ self._initialize_onedal_estimator()
345
+
346
+ # Falling back to daal4py if the device is CPU and alpha is array-like
347
+ # since onedal does not yet support non-scalars for alpha, thus
348
+ # should only be used for GPU/CPU with scalar alpha to not limit the functionality
349
+ cpu_device = queue is None or queue.sycl_device.is_cpu
350
+ if cpu_device and not _is_numeric_scalar(self.alpha):
351
+ self._daal_fit(X, y)
352
+ else:
353
+ self._onedal_estimator.fit(X, y, queue=queue)
354
+
355
+ self._save_attributes()
356
+
357
+ def _onedal_predict(self, X, queue=None):
358
+ if sklearn_check_version("1.0"):
359
+ X = self._validate_data(X, accept_sparse=False, reset=False)
360
+
361
+ if not hasattr(self, "_onedal_estimator"):
362
+ self._initialize_onedal_estimator()
363
+ self._onedal_estimator.coef_ = self.coef_
364
+ self._onedal_estimator.intercept_ = self.intercept_
365
+
366
+ res = self._onedal_estimator.predict(X, queue=queue)
367
+ return res
368
+
369
+ def _onedal_score(self, X, y, sample_weight=None, queue=None):
370
+ return r2_score(
371
+ y, self._onedal_predict(X, queue=queue), sample_weight=sample_weight
372
+ )
373
+
374
+ @property
375
+ def coef_(self):
376
+ return self._coef
377
+
378
+ @coef_.setter
379
+ def coef_(self, value):
380
+ if hasattr(self, "_onedal_estimator"):
381
+ self._onedal_estimator.coef_ = value
382
+ # checking if the model is already fitted and if so, deleting the model
383
+ if hasattr(self._onedal_estimator, "_onedal_model"):
384
+ del self._onedal_estimator._onedal_model
385
+ self._coef = value
386
+
387
+ @property
388
+ def intercept_(self):
389
+ return self._intercept
390
+
391
+ @intercept_.setter
392
+ def intercept_(self, value):
393
+ if hasattr(self, "_onedal_estimator"):
394
+ self._onedal_estimator.intercept_ = value
395
+ # checking if the model is already fitted and if so, deleting the model
396
+ if hasattr(self._onedal_estimator, "_onedal_model"):
397
+ del self._onedal_estimator._onedal_model
398
+ self._intercept = value
399
+
400
+ def _save_attributes(self):
401
+ self.n_features_in_ = self._onedal_estimator.n_features_in_
402
+ self._coef = self._onedal_estimator.coef_
403
+ self._intercept = self._onedal_estimator.intercept_
404
+
405
+ fit.__doc__ = sklearn_Ridge.fit.__doc__
406
+ predict.__doc__ = sklearn_Ridge.predict.__doc__
407
+ score.__doc__ = sklearn_Ridge.score.__doc__
408
+
409
+ else:
410
+ from daal4py.sklearn.linear_model._ridge import Ridge
411
+ from onedal._device_offload import support_usm_ndarray
412
+
413
+ Ridge.fit = support_usm_ndarray(queue_param=False)(Ridge.fit)
414
+ Ridge.predict = support_usm_ndarray(queue_param=False)(Ridge.predict)
415
+ Ridge.score = support_usm_ndarray(queue_param=False)(Ridge.score)
416
+
417
+ logging.warning(
418
+ "Preview Ridge requires oneDAL version >= 2024.6 but it was not found"
419
+ )