/
multiclass.py
345 lines (295 loc) · 12.4 KB
/
multiclass.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import cuml.internals
from cuml.internals.array import CumlArray
from cuml.internals.base import Base
from cuml.internals.import_utils import has_sklearn
from cuml.internals.mixins import ClassifierMixin
from cuml.common.doc_utils import generate_docstring
from cuml.common import (
input_to_host_array,
input_to_host_array_with_sparse_support,
)
from cuml.internals.input_utils import (
input_to_cupy_array,
determine_array_type_full,
)
from cuml.internals.array_sparse import SparseCumlArray
from cuml.internals import _deprecate_pos_args
class MulticlassClassifier(Base, ClassifierMixin):
"""
Wrapper around scikit-learn multiclass classifiers that allows to
choose different multiclass strategies.
The input can be any kind of cuML compatible array, and the output type
follows cuML's output type configuration rules.
Berofe passing the data to scikit-learn, it is converted to host (numpy)
array. Under the hood the data is partitioned for binary classification,
and it is transformed back to the device by the cuML estimator. These
copies back and forth the device and the host have some overhead. For more
details see issue https://github.com/rapidsai/cuml/issues/2876.
Examples
--------
.. code-block:: python
>>> from cuml.linear_model import LogisticRegression
>>> from cuml.multiclass import MulticlassClassifier
>>> from cuml.datasets.classification import make_classification
>>> X, y = make_classification(n_samples=10, n_features=6,
... n_informative=4, n_classes=3,
... random_state=137)
>>> cls = MulticlassClassifier(LogisticRegression(), strategy='ovo')
>>> cls.fit(X,y)
MulticlassClassifier()
>>> cls.predict(X)
array([2, 0, 2, 2, 2, 1, 1, 0, 1, 1])
Parameters
----------
estimator : cuML estimator
handle : cuml.Handle
Specifies the cuml.handle that holds internal CUDA state for
computations in this model. Most importantly, this specifies the CUDA
stream that will be used for the model's computations, so users can
run different models concurrently in different streams by creating
handles in several streams.
If it is None, a new one is created.
verbose : int or boolean, default=False
Sets logging level. It must be one of `cuml.common.logger.level_*`.
See :ref:`verbosity-levels` for more info.
output_type : {'input', 'array', 'dataframe', 'series', 'df_obj', \
'numba', 'cupy', 'numpy', 'cudf', 'pandas'}, default=None
Return results and set estimator attributes to the indicated output
type. If None, the output type set at the module level
(`cuml.global_settings.output_type`) will be used. See
:ref:`output-data-type-configuration` for more info.
strategy: string {'ovr', 'ovo'}, default='ovr'
Multiclass classification strategy: 'ovr': one vs. rest or 'ovo': one
vs. one
Attributes
----------
classes_ : float, shape (`n_classes_`)
Array of class labels.
n_classes_ : int
Number of classes.
"""
@_deprecate_pos_args(version="21.06")
def __init__(
self,
estimator,
*,
handle=None,
verbose=False,
output_type=None,
strategy="ovr",
):
super().__init__(
handle=handle, verbose=verbose, output_type=output_type
)
self.strategy = strategy
self.estimator = estimator
@property
@cuml.internals.api_base_return_array_skipall
def classes_(self):
return self.multiclass_estimator.classes_
@property
@cuml.internals.api_base_return_any_skipall
def n_classes_(self):
return self.multiclass_estimator.n_classes_
@generate_docstring(y="dense_anydtype")
def fit(self, X, y) -> "MulticlassClassifier":
"""
Fit a multiclass classifier.
"""
if not has_sklearn():
raise ImportError(
"Scikit-learn is needed to use "
"MulticlassClassifier derived classes."
)
import sklearn.multiclass
if self.strategy == "ovr":
self.multiclass_estimator = sklearn.multiclass.OneVsRestClassifier(
self.estimator, n_jobs=None
)
elif self.strategy == "ovo":
self.multiclass_estimator = sklearn.multiclass.OneVsOneClassifier(
self.estimator, n_jobs=None
)
else:
raise ValueError(
"Invalid multiclass strategy "
+ str(self.strategy)
+ ", must be one of "
'{"ovr", "ovo"}'
)
X = input_to_host_array_with_sparse_support(X)
y = input_to_host_array(y).array
with cuml.internals.exit_internal_api():
self.multiclass_estimator.fit(X, y)
return self
@generate_docstring(
return_values={
"name": "preds",
"type": "dense",
"description": "Predicted values",
"shape": "(n_samples, 1)",
}
)
def predict(self, X) -> CumlArray:
"""
Predict using multi class classifier.
"""
X = input_to_host_array_with_sparse_support(X)
with cuml.internals.exit_internal_api():
return self.multiclass_estimator.predict(X)
@generate_docstring(
return_values={
"name": "results",
"type": "dense",
"description": "Decision function \
values",
"shape": "(n_samples, 1)",
}
)
def decision_function(self, X) -> CumlArray:
"""
Calculate the decision function.
"""
X = input_to_host_array_with_sparse_support(X)
with cuml.internals.exit_internal_api():
return self.multiclass_estimator.decision_function(X)
def get_param_names(self):
return super().get_param_names() + ["estimator", "strategy"]
class OneVsRestClassifier(MulticlassClassifier):
"""
Wrapper around Sckit-learn's class with the same name. The input can be
any kind of cuML compatible array, and the output type follows cuML's
output type configuration rules.
Berofe passing the data to scikit-learn, it is converted to host (numpy)
array. Under the hood the data is partitioned for binary classification,
and it is transformed back to the device by the cuML estimator. These
copies back and forth the device and the host have some overhead. For more
details see issue https://github.com/rapidsai/cuml/issues/2876.
For documentation see `scikit-learn's OneVsRestClassifier
<https://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsRestClassifier.html>`_.
Examples
--------
.. code-block:: python
>>> from cuml.linear_model import LogisticRegression
>>> from cuml.multiclass import OneVsRestClassifier
>>> from cuml.datasets.classification import make_classification
>>> X, y = make_classification(n_samples=10, n_features=6,
... n_informative=4, n_classes=3,
... random_state=137)
>>> cls = OneVsRestClassifier(LogisticRegression())
>>> cls.fit(X,y)
OneVsRestClassifier()
>>> cls.predict(X)
array([2, 0, 2, 2, 2, 1, 1, 0, 1, 1])
Parameters
----------
estimator : cuML estimator
handle : cuml.Handle
Specifies the cuml.handle that holds internal CUDA state for
computations in this model. Most importantly, this specifies the CUDA
stream that will be used for the model's computations, so users can
run different models concurrently in different streams by creating
handles in several streams.
If it is None, a new one is created.
verbose : int or boolean, default=False
Sets logging level. It must be one of `cuml.common.logger.level_*`.
See :ref:`verbosity-levels` for more info.
output_type : {'input', 'array', 'dataframe', 'series', 'df_obj', \
'numba', 'cupy', 'numpy', 'cudf', 'pandas'}, default=None
Return results and set estimator attributes to the indicated output
type. If None, the output type set at the module level
(`cuml.global_settings.output_type`) will be used. See
:ref:`output-data-type-configuration` for more info.
"""
@_deprecate_pos_args(version="21.06")
def __init__(
self, estimator, *args, handle=None, verbose=False, output_type=None
):
super().__init__(
estimator,
*args,
handle=handle,
verbose=verbose,
output_type=output_type,
strategy="ovr",
)
def get_param_names(self):
param_names = super().get_param_names()
param_names.remove("strategy")
return param_names
class OneVsOneClassifier(MulticlassClassifier):
"""
Wrapper around Sckit-learn's class with the same name. The input can be
any kind of cuML compatible array, and the output type follows cuML's
output type configuration rules.
Berofe passing the data to scikit-learn, it is converted to host (numpy)
array. Under the hood the data is partitioned for binary classification,
and it is transformed back to the device by the cuML estimator. These
copies back and forth the device and the host have some overhead. For more
details see issue https://github.com/rapidsai/cuml/issues/2876.
For documentation see `scikit-learn's OneVsOneClassifier
<https://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsOneClassifier.html>`_.
Examples
--------
.. code-block:: python
>>> from cuml.linear_model import LogisticRegression
>>> from cuml.multiclass import OneVsOneClassifier
>>> from cuml.datasets.classification import make_classification
>>> X, y = make_classification(n_samples=10, n_features=6,
... n_informative=4, n_classes=3,
... random_state=137)
>>> cls = OneVsOneClassifier(LogisticRegression())
>>> cls.fit(X,y)
OneVsOneClassifier()
>>> cls.predict(X)
array([2, 0, 2, 2, 2, 1, 1, 0, 1, 1])
Parameters
----------
estimator : cuML estimator
handle : cuml.Handle
Specifies the cuml.handle that holds internal CUDA state for
computations in this model. Most importantly, this specifies the CUDA
stream that will be used for the model's computations, so users can
run different models concurrently in different streams by creating
handles in several streams.
If it is None, a new one is created.
verbose : int or boolean, default=False
Sets logging level. It must be one of `cuml.common.logger.level_*`.
See :ref:`verbosity-levels` for more info.
output_type : {'input', 'array', 'dataframe', 'series', 'df_obj', \
'numba', 'cupy', 'numpy', 'cudf', 'pandas'}, default=None
Return results and set estimator attributes to the indicated output
type. If None, the output type set at the module level
(`cuml.global_settings.output_type`) will be used. See
:ref:`output-data-type-configuration` for more info.
"""
@_deprecate_pos_args(version="21.06")
def __init__(
self, estimator, *args, handle=None, verbose=False, output_type=None
):
super().__init__(
estimator,
*args,
handle=handle,
verbose=verbose,
output_type=output_type,
strategy="ovo",
)
def get_param_names(self):
param_names = super().get_param_names()
param_names.remove("strategy")
return param_names