/
prediction.pyx
477 lines (383 loc) · 18.6 KB
/
prediction.pyx
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# Copyright (c) 2021-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.
#
# distutils: language = c++
from libc.stdint cimport uintptr_t
from cuml.internals.safe_imports import cpu_only_import
np = cpu_only_import('numpy')
from cuml.internals.safe_imports import gpu_only_import
cp = gpu_only_import('cupy')
from cuml.internals.array import CumlArray
from cuml.common import (
input_to_cuml_array,
input_to_host_array
)
from cuml.internals.device_type import DeviceType
from cuml.internals.import_utils import has_hdbscan
from cuml.internals import logger
import cuml
IF GPUBUILD == 1:
from cython.operator cimport dereference as deref
from pylibraft.common.handle cimport handle_t
from cuml.metrics.distance_type cimport DistanceType
from pylibraft.common.handle cimport handle_t
from pylibraft.common.handle import Handle
cdef extern from "cuml/cluster/hdbscan.hpp" namespace "ML::HDBSCAN::Common":
cdef cppclass CondensedHierarchy[value_idx, value_t]:
CondensedHierarchy(
const handle_t &handle, size_t n_leaves)
value_idx *get_parents()
value_idx *get_children()
value_t *get_lambdas()
value_idx get_n_edges()
cdef cppclass hdbscan_output[int, float]:
hdbscan_output(const handle_t &handle,
int n_leaves,
int *labels,
float *probabilities,
int *children,
int *sizes,
float *deltas,
int *mst_src,
int *mst_dst,
float *mst_weights)
int get_n_leaves()
int get_n_clusters()
float *get_stabilities()
int *get_labels()
int *get_inverse_label_map()
float *get_core_dists()
CondensedHierarchy[int, float] &get_condensed_tree()
cdef cppclass PredictionData[int, float]:
PredictionData(const handle_t &handle,
int m,
int n,
float *core_dists)
size_t n_rows
size_t n_cols
cdef extern from "cuml/cluster/hdbscan.hpp" namespace "ML":
void compute_all_points_membership_vectors(
const handle_t &handle,
CondensedHierarchy[int, float] &condensed_tree,
PredictionData[int, float] &prediction_data_,
float* X,
DistanceType metric,
float* membership_vec,
size_t batch_size)
void compute_membership_vector(
const handle_t& handle,
CondensedHierarchy[int, float] &condensed_tree,
PredictionData[int, float] &prediction_data,
float* X,
float* points_to_predict,
size_t n_prediction_points,
int min_samples,
DistanceType metric,
float* membership_vec,
size_t batch_size)
void out_of_sample_predict(const handle_t &handle,
CondensedHierarchy[int, float] &condensed_tree,
PredictionData[int, float] &prediction_data,
float* X,
int* labels,
float* points_to_predict,
size_t n_prediction_points,
DistanceType metric,
int min_samples,
int* out_labels,
float* out_probabilities)
_metrics_mapping = {
'l1': DistanceType.L1,
'cityblock': DistanceType.L1,
'manhattan': DistanceType.L1,
'l2': DistanceType.L2SqrtExpanded,
'euclidean': DistanceType.L2SqrtExpanded,
'cosine': DistanceType.CosineExpanded
}
def all_points_membership_vectors(clusterer, batch_size=4096):
"""
Predict soft cluster membership vectors for all points in the
original dataset the clusterer was trained on. This function is more
efficient by making use of the fact that all points are already in the
condensed tree, and processing in bulk.
Parameters
----------
clusterer : HDBSCAN
A clustering object that has been fit to the data and
had ``prediction_data=True`` set.
batch_size : int, optional, default=min(4096, n_rows)
Lowers memory requirement by computing distance-based membership
in smaller batches of points in the training data. For example, a batch
size of 1,000 computes distance based memberships for 1,000 points at a
time. The default batch size is 4,096.
Returns
-------
membership_vectors : array (n_samples, n_clusters)
The probability that point ``i`` of the original dataset is a member of
cluster ``j`` is in ``membership_vectors[i, j]``.
"""
if batch_size <= 0:
raise ValueError("batch_size must be > 0")
device_type = cuml.global_settings.device_type
# cpu infer, cpu/gpu train
if device_type == DeviceType.host:
assert has_hdbscan(raise_if_unavailable=True)
from hdbscan.prediction import all_points_membership_vectors \
as cpu_all_points_membership_vectors
# trained on gpu
if not hasattr(clusterer, "_cpu_model"):
# the reference HDBSCAN implementations uses @property
# for attributes without setters available for them,
# so they can't be transferred from the GPU model
# to the CPU model
raise ValueError("Inferring on CPU is not supported yet when the "
"model has been trained on GPU")
# this took a long debugging session to figure out, but
# this method on cpu does not work without this copy for some reason
clusterer._cpu_model.prediction_data_.raw_data = \
clusterer._cpu_model.prediction_data_.raw_data.copy()
return cpu_all_points_membership_vectors(clusterer._cpu_model)
elif device_type == DeviceType.device:
# trained on cpu
if hasattr(clusterer, "_cpu_model"):
clusterer._prep_cpu_to_gpu_prediction()
if not clusterer.fit_called_:
raise ValueError("The clusterer is not fit on data. "
"Please call clusterer.fit first")
if not clusterer.prediction_data:
raise ValueError("PredictionData not generated. "
"Please call clusterer.fit again with "
"prediction_data=True or call "
"clusterer.generate_prediction_data()")
if clusterer.n_clusters_ == 0:
return np.zeros(clusterer.n_rows, dtype=np.float32)
cdef uintptr_t _input_ptr = clusterer.X_m.ptr
membership_vec = CumlArray.empty(
(clusterer.n_rows * clusterer.n_clusters_,),
dtype="float32")
cdef uintptr_t _membership_vec_ptr = membership_vec.ptr
IF GPUBUILD == 1:
cdef PredictionData *prediction_data_ = \
<PredictionData*><size_t>clusterer.prediction_data_ptr
cdef CondensedHierarchy[int, float] *condensed_tree = \
<CondensedHierarchy[int, float]*><size_t> clusterer.condensed_tree_ptr
cdef handle_t* handle_ = <handle_t*><size_t>clusterer.handle.getHandle()
compute_all_points_membership_vectors(handle_[0],
deref(condensed_tree),
deref(prediction_data_),
<float*> _input_ptr,
_metrics_mapping[clusterer.metric],
<float*> _membership_vec_ptr,
batch_size)
clusterer.handle.sync()
return membership_vec.to_output(
output_type="numpy",
output_dtype="float32").reshape((clusterer.n_rows,
clusterer.n_clusters_))
def membership_vector(clusterer, points_to_predict, batch_size=4096, convert_dtype=True):
"""
Predict soft cluster membership. The result produces a vector
for each point in ``points_to_predict`` that gives a probability that
the given point is a member of a cluster for each of the selected clusters
of the ``clusterer``.
Parameters
----------
clusterer : HDBSCAN
A clustering object that has been fit to the data and
either had ``prediction_data=True`` set, or called the
``generate_prediction_data`` method after the fact.
points_to_predict : array, or array-like (n_samples, n_features)
The new data points to predict cluster labels for. They should
have the same dimensionality as the original dataset over which
clusterer was fit.
batch_size : int, optional, default=min(4096, n_points_to_predict)
Lowers memory requirement by computing distance-based membership
in smaller batches of points in the prediction data. For example, a
batch size of 1,000 computes distance based memberships for 1,000
points at a time. The default batch size is 4,096.
Returns
-------
membership_vectors : array (n_samples, n_clusters)
The probability that point ``i`` is a member of cluster ``j`` is
in ``membership_vectors[i, j]``.
"""
device_type = cuml.global_settings.device_type
# cpu infer, cpu/gpu train
if device_type == DeviceType.host:
assert has_hdbscan(raise_if_unavailable=True)
from hdbscan.prediction import membership_vector \
as cpu_membership_vector
# trained on gpu
if not hasattr(clusterer, "_cpu_model"):
# the reference HDBSCAN implementations uses @property
# for attributes without setters available for them,
# so they can't be transferred from the GPU model
# to the CPU model
raise ValueError("Inferring on CPU is not supported yet when the "
"model has been trained on GPU")
host_points_to_predict = input_to_host_array(points_to_predict).array
return cpu_membership_vector(clusterer._cpu_model,
host_points_to_predict)
elif device_type == DeviceType.device:
# trained on cpu
if hasattr(clusterer, "_cpu_model"):
clusterer._prep_cpu_to_gpu_prediction()
if not clusterer.fit_called_:
raise ValueError("The clusterer is not fit on data. "
"Please call clusterer.fit first")
if not clusterer.prediction_data:
raise ValueError("PredictionData not generated. "
"Please call clusterer.fit again with "
"prediction_data=True")
if batch_size <= 0:
raise ValueError("batch_size must be > 0")
_points_to_predict_m, n_prediction_points, n_cols, _ = \
input_to_cuml_array(points_to_predict, order='C',
check_dtype=[np.float32],
convert_to_dtype=(np.float32
if convert_dtype
else None))
if clusterer.n_clusters_ == 0:
return np.zeros(n_prediction_points, dtype=np.float32)
if n_cols != clusterer.n_cols:
raise ValueError('New points dimension does not match fit data!')
IF GPUBUILD == 1:
cdef uintptr_t _prediction_ptr = _points_to_predict_m.ptr
cdef uintptr_t _input_ptr = clusterer.X_m.ptr
membership_vec = CumlArray.empty(
(n_prediction_points * clusterer.n_clusters_,),
dtype="float32")
cdef uintptr_t _membership_vec_ptr = membership_vec.ptr
cdef CondensedHierarchy[int, float] *condensed_tree = \
<CondensedHierarchy[int, float]*><size_t> clusterer.condensed_tree_ptr
cdef PredictionData *prediction_data_ = \
<PredictionData*><size_t>clusterer.prediction_data_ptr
cdef handle_t* handle_ = <handle_t*><size_t>clusterer.handle.getHandle()
compute_membership_vector(handle_[0],
deref(condensed_tree),
deref(prediction_data_),
<float*> _input_ptr,
<float*> _prediction_ptr,
n_prediction_points,
clusterer.min_samples,
_metrics_mapping[clusterer.metric],
<float*> _membership_vec_ptr,
batch_size)
clusterer.handle.sync()
return membership_vec.to_output(
output_type="numpy",
output_dtype="float32").reshape((n_prediction_points,
clusterer.n_clusters_))
def approximate_predict(clusterer, points_to_predict, convert_dtype=True):
"""Predict the cluster label of new points. The returned labels
will be those of the original clustering found by ``clusterer``,
and therefore are not (necessarily) the cluster labels that would
be found by clustering the original data combined with
``points_to_predict``, hence the 'approximate' label.
If you simply wish to assign new points to an existing clustering
in the 'best' way possible, this is the function to use. If you
want to predict how ``points_to_predict`` would cluster with
the original data under HDBSCAN the most efficient existing approach
is to simply recluster with the new point(s) added to the original dataset.
Parameters
----------
clusterer : HDBSCAN
A clustering object that has been fit to the data and
had ``prediction_data=True`` set.
points_to_predict : array, or array-like (n_samples, n_features)
The new data points to predict cluster labels for. They should
have the same dimensionality as the original dataset over which
clusterer was fit.
Returns
-------
labels : array (n_samples,)
The predicted labels of the ``points_to_predict``
probabilities : array (n_samples,)
The soft cluster scores for each of the ``points_to_predict``
"""
device_type = cuml.global_settings.device_type
# cpu infer, cpu/gpu train
if device_type == DeviceType.host:
assert has_hdbscan(raise_if_unavailable=True)
from hdbscan.prediction import approximate_predict \
as cpu_approximate_predict
# trained on gpu
if not hasattr(clusterer, "_cpu_model"):
# the reference HDBSCAN implementations uses @property
# for attributes without setters available for them,
# so they can't be transferred from the GPU model
# to the CPU model
raise ValueError("Inferring on CPU is not supported yet when the "
"model has been trained on GPU")
host_points_to_predict = input_to_host_array(points_to_predict).array
return cpu_approximate_predict(clusterer._cpu_model,
host_points_to_predict)
elif device_type == DeviceType.device:
# trained on cpu
if hasattr(clusterer, "_cpu_model"):
clusterer._prep_cpu_to_gpu_prediction()
if not clusterer.fit_called_:
raise ValueError("The clusterer is not fit on data. "
"Please call clusterer.fit first")
if not clusterer.prediction_data:
raise ValueError("PredictionData not generated. "
"Please call clusterer.fit again with "
"prediction_data=True")
if clusterer.n_clusters_ == 0:
logger.warn(
'Clusterer does not have any defined clusters, new data '
'will be automatically predicted as outliers.'
)
_points_to_predict_m, n_prediction_points, n_cols, _ = \
input_to_cuml_array(points_to_predict, order='C',
check_dtype=[np.float32],
convert_to_dtype=(np.float32
if convert_dtype
else None))
if n_cols != clusterer.n_cols:
raise ValueError('New points dimension does not match fit data!')
cdef uintptr_t _prediction_ptr = _points_to_predict_m.ptr
cdef uintptr_t _input_ptr = clusterer.X_m.ptr
prediction_labels = CumlArray.empty(
(n_prediction_points,),
dtype="int32")
cdef uintptr_t _prediction_labels_ptr = prediction_labels.ptr
prediction_probs = CumlArray.empty(
(n_prediction_points,),
dtype="float32")
cdef uintptr_t _prediction_probs_ptr = prediction_probs.ptr
labels, _, _, _ = input_to_cuml_array(clusterer.labels_,
order="C",
convert_to_dtype=np.int32)
cdef uintptr_t _labels_ptr = labels.ptr
IF GPUBUILD == 1:
cdef CondensedHierarchy[int, float] *condensed_tree = \
<CondensedHierarchy[int, float]*><size_t> clusterer.condensed_tree_ptr
cdef PredictionData *prediction_data_ = \
<PredictionData*><size_t>clusterer.prediction_data_ptr
cdef handle_t* handle_ = <handle_t*><size_t>clusterer.handle.getHandle()
out_of_sample_predict(handle_[0],
deref(condensed_tree),
deref(prediction_data_),
<float*> _input_ptr,
<int*> _labels_ptr,
<float*> _prediction_ptr,
n_prediction_points,
_metrics_mapping[clusterer.metric],
clusterer.min_samples,
<int*> _prediction_labels_ptr,
<float*> _prediction_probs_ptr)
clusterer.handle.sync()
return prediction_labels.to_output(output_type="numpy"), \
prediction_probs.to_output(output_type="numpy", output_dtype="float32")