-
Notifications
You must be signed in to change notification settings - Fork 23
/
decision_tree.py
1482 lines (1367 loc) · 59.7 KB
/
decision_tree.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
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
import pickle
import numpy as np
from sklearn.tree import DecisionTreeClassifier as SklearnDTClassifier
from sklearn.tree import DecisionTreeRegressor as SklearnDTRegressor
from pycompss.api.parameter import INOUT, COLLECTION_INOUT, COLLECTION_IN
from sklearn.utils import check_random_state
from pycompss.api.api import (compss_delete_object,
compss_wait_on, compss_barrier)
from dislib.data.array import Array
from pycompss.api.task import task
from pycompss.api.on_failure import on_failure
from pycompss.api.constraint import constraint
import scipy
from pycompss.api.parameter import Depth, Type
from dislib.trees.distributed.terasort import terasort
import dislib.data.util.model as utilmodel
class BaseDecisionTree:
"""Base class for distributed decision trees.
Warning: This class should not be used directly.
Use derived classes instead.
"""
def __init__(
self,
try_features,
max_depth,
distr_depth,
sklearn_max,
bootstrap,
random_state,
base_node,
base_tree,
n_classes=None,
range_min=None,
range_max=None,
n_split_points="auto",
split_computation="raw",
sync_after_fit=True,
):
self.n_classes = n_classes
self.try_features = try_features
self.max_depth = max_depth
self.sklearn_max = sklearn_max
self.distr_depth = distr_depth
self.bootstrap = bootstrap
self.random_state = random_state
self.base_node = base_node
self.base_tree = base_tree
self.n_features = None
self.tree = None
self.nodes_info = None
self.range_min = range_min
self.range_max = range_max
self.n_split_points = n_split_points
self.split_computation = split_computation
self.sync_after_fit = sync_after_fit
def fit(self, x, y):
"""Fits the DecisionTree.
Parameters
----------
x : ds-array
Samples of the dataset.
y: ds-array
Labels of the dataset.
"""
if self.range_max is None:
self.range_max = x.max()
if self.range_min is None:
self.range_min = x.min()
if self.n_split_points == "auto":
self.n_split_points = int(math.log(x.shape[0]))
elif self.n_split_points == "sqrt":
self.n_split_points = int(math.sqrt(x.shape[0]))
elif self.n_split_points < 1 and self.n_split_points > 0:
self.n_split_points = int(self.n_split_points * x.shape[0])
elif isinstance(self.n_split_points, int):
pass
self.number_attributes = x.shape[1]
self.tree = self.base_node()
branches = [[x, y, self.tree]]
nodes_info = []
selection = _sample_selection(x, random_state=self.random_state,
bootstrap=self.bootstrap)
num_buckets = x._n_blocks[0] * x._n_blocks[1]
for i in range(self.distr_depth):
branches_pair = []
for idx, branch_data in enumerate(branches):
x, y, actual_node = branch_data
node_info, results = _compute_split(
x, y,
n_classes=self.n_classes,
range_min=self.range_min,
range_max=self.range_max,
num_buckets=int(num_buckets/(i+1)),
m_try=self.try_features,
number_attributes=self.number_attributes,
indexes_selected=selection,
number_split_points=int(self.n_split_points*(i+1)),
split_computation=self.split_computation,
random_state=self.random_state)
actual_node.content = len(nodes_info)
splits_computed = []
actual_node.left = self.base_node()
actual_node.right = self.base_node()
for k, sides in enumerate(results):
l, r = sides
splits_computed.append(l)
splits_computed.append(r)
if k == 0:
splits_computed.append(actual_node.left)
else:
splits_computed.append(actual_node.right)
branches_pair.append(splits_computed)
splits_computed = []
nodes_info.append(node_info)
branches = branches_pair
for branch in branches:
x, y, actual_node = branch
construct_subtree(x, y, actual_node, self.try_features,
self.distr_depth, max_depth=self.max_depth,
random_state=self.random_state)
nodes_info.append(actual_node)
if self.sync_after_fit:
compss_barrier()
self.nodes_info = nodes_info
def predict(self, x, collect=False):
"""Predicts target values or classes for the given samples using
a fitted tree.
Parameters
----------
x_row : ds-array
A row block of samples.
Returns
-------
predicted : ndarray
An array with the predicted classes or values for the given
samples. For classification, the values are codes of the fitted
dislib.classification.rf.data.RfDataset. The returned object can
be a pycompss.runtime.Future object.
"""
assert self.tree is not None, "The decision tree is not fitted."
block_predictions = []
for x_block in x._blocks:
block_predictions.append(_predict_tree_class(x_block,
self.nodes_info,
0, self.n_classes))
if collect:
block_predictions = compss_wait_on(block_predictions)
return block_predictions
class DecisionTreeClassifier(BaseDecisionTree):
"""A distributed decision tree classifier.
Parameters
----------
try_features : int
The number of features to consider when looking for the best split.
Note: the search for a split does not stop until at least one
valid partition of the node samples is found, even if it requires
to effectively inspect more than ``try_features`` features.
max_depth : int
The maximum depth of the tree. If np.inf, then nodes are expanded
until all leaves are pure.
distr_depth : int
Number of levels of the tree in which the nodes are split in a
distributed way.
bootstrap : bool
Randomly select n_instances samples with repetition (used in random
forests).
random_state : RandomState instance
The random number generator.
n_classes : int
Number of classes that appear on the dataset.
range_min : ds-array or np.array
Contains the minimum values of the different attributes of the dataset
range_max : ds-array or np.array
Contains the maximum values of the different attributes of the dataset
n_split_points : String or int
Number of split points to evaluate.
"auto", "sqrt" or integer value.
split_computation : String
"raw", "gaussian_approximation" or "uniform_approximation"
distribution of the values followed by the split points selected.
sync_after_fit : bool
Synchronize or not after the training.
Attributes
----------
n_features : int
The number of features of the dataset. It can be a
pycompss.runtime.Future object.
tree : None or _Node
The root node of the tree after the tree is fitted.
nodes_info : None or list of _InnerNodeInfo, _LeafInfo and _Node
List of the node information for the nodes of the tree in the same
order as obtained in the fit() method, up to ``distr_depth`` depth.
After fit(), it is a pycompss.runtime.Future object.
Methods
-------
fit(dataset)
Fits the DecisionTreeClassifier.
predict(x_row)
Predicts classes for the given samples using a fitted tree.
predict_proba(x_row)
Predicts class probabilities for the given smaples using a
fitted tree.
"""
def __init__(
self,
n_classes,
try_features,
max_depth,
distr_depth,
sklearn_max,
bootstrap,
random_state,
range_max=None,
range_min=None,
n_split_points="auto",
split_computation="raw",
sync_after_fit=True,
):
super().__init__(
try_features,
max_depth,
distr_depth,
sklearn_max,
bootstrap,
random_state,
_ClassificationNode,
SklearnDTClassifier,
n_classes=n_classes,
range_min=range_min,
range_max=range_max,
n_split_points=n_split_points,
split_computation=split_computation,
sync_after_fit=sync_after_fit,
)
def predict_proba(self, x, collect=False):
"""Predicts class probabilities for a row block using a fitted tree.
Parameters
----------
x_row : ds-array
A row block of samples.
Returns
-------
predicted_proba : list
A list with the predicted probabilities for the
given samples.
It contains a numpy array (if collect=True)
or Future object (if collect=False) for each of the blocks
in the ds-array to predict. Thus the length
of the list is the same
as the number of blocks the ds-array contains.
The shape inside each prediction is
(len(x.reg_shape[0]), self.n_classes).
The returned object can be a pycompss.runtime.
Future object.
"""
assert self.tree is not None, "The decision tree is not fitted."
block_predictions = []
for x_block in x._blocks:
block_predictions.append(_predict_proba_tree(x_block,
self.nodes_info,
0, self.n_classes))
if collect:
block_predictions = compss_wait_on(block_predictions)
return block_predictions
class DecisionTreeRegressor(BaseDecisionTree):
"""A distributed decision tree regressor.
Parameters
----------
try_features : int
The number of features to consider when looking for the best split.
Note: the search for a split does not stop until at least one
valid partition of the node samples is found, even if it requires
to effectively inspect more than ``try_features`` features.
max_depth : int
The maximum depth of the tree. If np.inf, then nodes are expanded
until all leaves are pure.
distr_depth : int
Number of levels of the tree in which the nodes are split in a
distributed way.
bootstrap : bool
Randomly select n_instances samples with repetition (used in random
forests).
random_state : RandomState instance
The random number generator.
range_min : ds-array or np.array
Contains the minimum values of the different attributes of the dataset
range_max : ds-array or np.array
Contains the maximum values of the different attributes of the dataset
n_split_points : String or int
Number of split points to evaluate.
"auto", "sqrt" or integer value.
split_computation : String
"raw", "gaussian_approximation" or "uniform_approximation"
distribution of the values followed by the split points selected.
sync_after_fit : bool
Synchronize or not after the training.
Attributes
----------
n_features : int
The number of features of the dataset. It can be a
pycompss.runtime.Future object.
tree : None or _Node
The root node of the tree after the tree is fitted.
nodes_info : None or list of _InnerNodeInfo, _Node and _LeafInfo
List of the node information for the nodes of the tree in the same
order as obtained in the fit() method, up to ``distr_depth`` depth.
After fit(), it is a pycompss.runtime.Future object.
Methods
-------
fit(dataset)
Fits the DecisionTreeRegressor.
predict(x_row)
Predicts target values for the given samples using a fitted tree.
"""
def __init__(
self,
try_features,
max_depth,
distr_depth,
sklearn_max,
bootstrap,
random_state,
range_max=None,
range_min=None,
n_split_points="auto",
split_computation="raw",
sync_after_fit=True
):
super().__init__(
try_features,
max_depth,
distr_depth,
sklearn_max,
bootstrap,
random_state,
_RegressionNode,
SklearnDTRegressor,
n_classes=None,
range_min=range_min,
range_max=range_max,
n_split_points=n_split_points,
split_computation=split_computation,
sync_after_fit=sync_after_fit,
)
def fit(self, x, y):
"""Fits the DecisionTreeRegressor.
Parameters
----------
x : ds-array
Samples of the dataset.
y: ds-array
Labels of the dataset.
"""
if self.range_max is None:
self.range_max = x.max()
if self.range_min is None:
self.range_min = x.min()
if self.n_split_points == "auto":
self.n_split_points = int(math.log(x.shape[0]))
elif self.n_split_points == "sqrt":
self.n_split_points = int(math.sqrt(x.shape[0]))
elif self.n_split_points < 1 and self.n_split_points > 0:
self.n_split_points = int(self.n_split_points*x.shape[0])
elif isinstance(self.n_split_points, int):
pass
self.number_attributes = x.shape[1]
self.tree = self.base_node()
branches = [[x, y, self.tree]]
nodes_info = []
selection = _sample_selection(x,
random_state=self.random_state,
bootstrap=self.bootstrap)
num_buckets = x._n_blocks[0] * x._n_blocks[1]
for i in range(self.distr_depth):
branches_pair = []
for idx, branch_data in enumerate(branches):
x, y, actual_node = branch_data
node_info, results = _compute_split_regressor(
x, y, range_min=self.range_min, range_max=self.range_max,
num_buckets=int(num_buckets/(i+1)),
m_try=self.try_features,
number_attributes=self.number_attributes,
indexes_selected=selection,
number_split_points=int(self.n_split_points*(i+1)),
split_computation=self.split_computation,
random_state=self.random_state)
actual_node.content = len(nodes_info)
splits_computed = []
actual_node.left = self.base_node()
actual_node.right = self.base_node()
for k, sides in enumerate(results):
l, r = sides
splits_computed.append(l)
splits_computed.append(r)
if k == 0:
splits_computed.append(actual_node.left)
else:
splits_computed.append(actual_node.right)
branches_pair.append(splits_computed)
splits_computed = []
nodes_info.append(node_info)
branches = branches_pair
for branch in branches:
x, y, actual_node = branch
construct_subtree(x, y, actual_node, self.try_features,
self.distr_depth, max_depth=self.max_depth,
random_state=self.random_state)
nodes_info.append(actual_node)
if self.sync_after_fit:
compss_barrier()
self.nodes_info = nodes_info
def _compute_split_regressor(x, y, num_buckets=4, range_min=0,
range_max=1,
indexes_selected=None,
number_attributes=2, m_try=2,
number_split_points=100,
split_computation="raw", random_state=1):
indexes_to_try = []
random_state = check_random_state(random_state)
untried_indices = np.setdiff1d(np.arange(
number_attributes), indexes_to_try)
index_selection = _feature_selection(
untried_indices, m_try, random_state
)
indexes_to_try.extend(index_selection)
node_info = _NodeInfo()
final_rights_x = [object()]
final_rights_y = [object()]
final_lefts_x = [object()]
final_lefts_y = [object()]
found_solution = np.array([0])
if num_buckets < 1:
num_buckets = 1
results = terasort(x, indexes_to_try,
range_min=range_min,
range_max=range_max,
indexes_selected=indexes_selected,
num_buckets=num_buckets)
split_points_per_attribute = []
for i in range(len(results[0])):
split_points_per_attribute.append(
get_split_point_various_attributes_bucket(
results[:, i],
number_split_points=number_split_points,
split_computation=split_computation))
[compss_delete_object(b) for results_2 in results for b in results_2]
del results
partial_results_left = []
partial_results_right = []
for idx, split_values in enumerate(split_points_per_attribute):
partial_results_left.append([])
partial_results_right.append([])
if isinstance(x, Array):
for index_blocks, block_s in enumerate(zip(x._blocks, y._blocks)):
block_x, block_y = block_s
left_class = [object() for _ in range(len(indexes_to_try))]
right_class = [object() for _ in range(len(indexes_to_try))]
classes_per_split(block_x, block_y, split_values,
left_class, right_class, indexes_to_try,
indexes_selected=indexes_selected,
index_blocks=index_blocks,
top_left_shape=x._top_left_shape[0],
reg_shape=x._reg_shape[0],
regression=True)
partial_results_left[idx].append(left_class)
partial_results_right[idx].append(right_class)
else:
for block_x, block_y in zip(x, y):
left_class = [object() for _ in range(len(indexes_to_try))]
right_class = [object() for _ in range(len(indexes_to_try))]
classes_per_split(block_x, block_y, split_values,
left_class, right_class, indexes_to_try,
regression=True)
partial_results_left[idx].append(left_class)
partial_results_right[idx].append(right_class)
partial_results_right_array = np.array(partial_results_right)
partial_results_left_array = np.array(partial_results_left)
store_mse_values = []
evaluation_of_splits = []
for idx in range(partial_results_right_array.shape[0]):
for j in range(partial_results_right_array.shape[2]):
global_gini_values, produces_split = (
merge_partial_results_compute_mse_both_sides(
partial_results_left_array[idx, :, j],
partial_results_right_array[idx, :, j]))
store_mse_values.append(global_gini_values)
evaluation_of_splits.append(produces_split)
del partial_results_right_array
del partial_results_left_array
[compss_delete_object(b) for results in partial_results_right for
result in results for b in result]
[compss_delete_object(b) for results in partial_results_left for
result in results for b in result]
best_attribute, position_m_g, bucket_minimum_gini, minimum_mse = (
get_minimum_measure(store_mse_values,
m_try,
gini=False))
optimal_split_point = select_optimal_split_point(
best_attribute, position_m_g, split_points_per_attribute,
bucket_minimum_gini)
compss_delete_object(position_m_g)
compss_delete_object(bucket_minimum_gini)
compss_delete_object(*evaluation_of_splits)
compss_delete_object(*store_mse_values)
compss_delete_object(*split_points_per_attribute)
rights_x = []
rights_y = []
lefts_x = []
lefts_y = []
right_sums = []
right_lengths = []
left_sums = []
left_lengths = []
if isinstance(x, Array):
for block_x, block_y in zip(x._blocks, y._blocks):
(right_x, right_y, left_x, left_y, compress_r, len_compress_r,
compress_l, len_compress_l) = (
apply_split_points_to_blocks_regression(block_x, block_y,
best_attribute,
optimal_split_point,
indexes_to_try))
rights_x.append([right_x])
rights_y.append([right_y])
lefts_x.append([left_x])
lefts_y.append([left_y])
right_sums.append(compress_r)
right_lengths.append(len_compress_r)
left_sums.append(compress_l)
left_lengths.append(len_compress_l)
else:
for block_x, block_y in zip(x, y):
(right_x, right_y, left_x, left_y, compress_r, len_compress_r,
compress_l, len_compress_l) = (
apply_split_points_to_blocks_regression(block_x, block_y,
best_attribute,
optimal_split_point,
indexes_to_try))
rights_x.append([right_x])
rights_y.append([right_y])
lefts_x.append([left_x])
lefts_y.append([left_y])
right_sums.append(compress_r)
right_lengths.append(len_compress_r)
left_sums.append(compress_l)
left_lengths.append(len_compress_l)
[compss_delete_object(x_data[0]) for x_data in x]
[compss_delete_object(y_data[0]) for y_data in y]
generate_nodes_with_data_compressed_regression(node_info, found_solution,
right_sums, right_lengths,
left_sums, left_lengths,
best_attribute,
indexes_to_try,
optimal_split_point)
final_rights_x[0] = rights_x
final_rights_y[0] = rights_y
final_lefts_x[0] = lefts_x
final_lefts_y[0] = lefts_y
evaluate_exception(found_solution, node_info, final_rights_x,
final_rights_y, final_lefts_x, final_lefts_y)
compss_delete_object(*right_sums)
compss_delete_object(*right_lengths)
compss_delete_object(*left_sums)
compss_delete_object(*left_lengths)
compss_delete_object(minimum_mse)
compss_delete_object(optimal_split_point)
compss_delete_object(best_attribute)
return node_info, [[final_lefts_x[0], final_lefts_y[0]],
[final_rights_x[0], final_rights_y[0]]]
def _compute_split(x, y, n_classes=None, num_buckets=4, range_min=0,
range_max=1,
indexes_selected=None, number_attributes=2, m_try=2,
number_split_points=100, split_computation="raw",
random_state=None):
indexes_to_try = []
random_state = check_random_state(random_state)
untried_indices = np.setdiff1d(
np.arange(number_attributes), indexes_to_try)
index_selection = _feature_selection(
untried_indices, m_try, random_state
)
indexes_to_try.extend(index_selection)
node_info = _NodeInfo()
final_rights_x = [object()]
final_rights_y = [object()]
final_lefts_x = [object()]
final_lefts_y = [object()]
found_solution = np.array([0])
if num_buckets < 1:
num_buckets = 1
results = terasort(x, index_selection, range_min=range_min,
range_max=range_max, indexes_selected=indexes_selected,
num_buckets=num_buckets)
split_points_per_attribute = []
for i in range(len(
results[0])):
split_points_per_attribute.append(
get_split_point_various_attributes_bucket(
results[:, i],
number_split_points=number_split_points,
split_computation=split_computation))
[compss_delete_object(b) for results_2 in results for b in results_2]
del results
partial_results_left = []
partial_results_right = []
for idx, split_values in enumerate(split_points_per_attribute):
partial_results_left.append([])
partial_results_right.append([])
if isinstance(x, Array):
for index_blocks, block_s in enumerate(zip(x._blocks, y._blocks)):
block_x, block_y = block_s
left_class = [object() for _ in range(len(indexes_to_try))]
right_class = [object() for _ in range(len(indexes_to_try))]
classes_per_split(block_x, block_y, split_values,
left_class, right_class, indexes_to_try,
indexes_selected=indexes_selected,
index_blocks=index_blocks,
top_left_shape=x._top_left_shape[0],
reg_shape=x._reg_shape[0])
partial_results_left[idx].append(left_class)
partial_results_right[idx].append(right_class)
else:
for block_x, block_y in zip(x, y):
left_class = [object() for _ in range(len(indexes_to_try))]
right_class = [object() for _ in range(len(indexes_to_try))]
classes_per_split(block_x, block_y, split_values, left_class,
right_class, indexes_to_try)
partial_results_left[idx].append(left_class)
partial_results_right[idx].append(right_class)
partial_results_right_array = np.array(partial_results_right)
partial_results_left_array = np.array(partial_results_left)
store_gini_values = []
evaluation_of_splits = []
for idx in range(partial_results_right_array.shape[0]):
for j in range(partial_results_right_array.shape[2]):
global_gini_values, produces_split = (
merge_partial_results_compute_gini_both_sides(
partial_results_left_array[idx, :, j],
partial_results_right_array[idx, :, j],
n_classes))
store_gini_values.append(global_gini_values)
evaluation_of_splits.append(produces_split)
del partial_results_right_array
del partial_results_left_array
[compss_delete_object(b) for results in partial_results_right for
result in results for b in result]
[compss_delete_object(b) for results in partial_results_left for
result in results for b in result]
best_attribute, position_m_g, bucket_minimum_gini, minimum_ginis = (
get_minimum_measure(store_gini_values, m_try, gini=True))
optimal_split_point = select_optimal_split_point(
best_attribute, position_m_g, split_points_per_attribute,
bucket_minimum_gini)
compss_delete_object(position_m_g)
compss_delete_object(bucket_minimum_gini)
compss_delete_object(minimum_ginis)
compss_delete_object(*evaluation_of_splits)
compss_delete_object(*store_gini_values)
compss_delete_object(*split_points_per_attribute)
rights_x = []
rights_y = []
lefts_x = []
lefts_y = []
compressed_right = []
compressed_left = []
if isinstance(x, Array):
for block_x, block_y in zip(x._blocks, y._blocks):
(right_x, right_y, left_x, left_y, compressed_r_y,
compressed_l_y) = apply_split_points_to_blocks(
block_x, block_y, best_attribute, optimal_split_point,
indexes_to_try, n_classes)
rights_x.append([right_x])
rights_y.append([right_y])
compressed_right.append(compressed_r_y)
compressed_left.append(compressed_l_y)
lefts_x.append([left_x])
lefts_y.append([left_y])
else:
for block_x, block_y in zip(x, y):
(right_x, right_y, left_x, left_y, compressed_r_y,
compressed_l_y) = apply_split_points_to_blocks(
block_x, block_y, best_attribute, optimal_split_point,
indexes_to_try, n_classes)
rights_x.append([right_x])
rights_y.append([right_y])
compressed_right.append(compressed_r_y)
compressed_left.append(compressed_l_y)
lefts_x.append([left_x])
lefts_y.append([left_y])
[compss_delete_object(x_data[0]) for x_data in x]
[compss_delete_object(y_data[0]) for y_data in y]
generate_nodes_with_data_compressed(node_info,
found_solution, compressed_right,
compressed_left, n_classes,
best_attribute,
indexes_to_try, optimal_split_point)
final_rights_x[0] = rights_x
final_rights_y[0] = rights_y
final_lefts_x[0] = lefts_x
final_lefts_y[0] = lefts_y
evaluate_exception(found_solution, node_info, final_rights_x,
final_rights_y, final_lefts_x, final_lefts_y)
compss_delete_object(best_attribute)
compss_delete_object(evaluation_of_splits)
compss_delete_object(optimal_split_point)
compss_delete_object(*compressed_left)
compss_delete_object(*compressed_right)
compss_delete_object(minimum_ginis)
return node_info, [[final_lefts_x[0], final_lefts_y[0]],
[final_rights_x[0], final_rights_y[0]]]
def _feature_selection(untried_indices, m_try, random_state):
selection_len = min(m_try, len(untried_indices))
return random_state.choice(
untried_indices, size=selection_len, replace=False
)
def gini_function_compressed(y, classes):
if not len(y) != 0:
return 0
probs = []
total_y = np.sum(y)
for idx in range(len(classes)):
if len(y) > idx:
probs.append(y[idx]/total_y)
p = np.array(probs)
return 1 - ((p * p).sum())
def _compute_leaf_info(y_s, n_classes, occurrences=None):
if n_classes is not None:
y_s = y_s.squeeze()
mode = np.argmax(y_s)
return _LeafInfo(len(y_s), y_s, mode)
else:
return _LeafInfo(occurrences, None, y_s)
@constraint(computing_units="${ComputingUnits}")
@task(x=COLLECTION_IN, node=COLLECTION_IN, returns=1)
def _predict_tree_class(x, node, node_content_num, n_classes=None,
rights=0, depth=0):
if node_content_num == 0:
node_content_num = node_content_num + 1
else:
node_content_num = node_content_num * 2 + rights
x = np.block(x)
node_content = node[node_content_num - 1]
if len(x) == 0:
if n_classes is not None:
return np.empty((0, n_classes), dtype=np.float64)
else:
return np.empty((0,), dtype=np.float64)
if isinstance(node_content, _NodeInfo):
if isinstance(node_content.get(), _LeafInfo):
if n_classes is not None:
return np.full((len(x), n_classes), node_content.get().target)
return np.full((len(x),), node_content.get().target)
elif isinstance(node_content.get(), _InnerNodeInfo):
if n_classes is not None:
pred = np.empty((x.shape[0], n_classes), dtype=np.float64)
l_msk = (x[:, node_content.get().index:
(node_content.get().index + 1)] <=
node_content.get().value)
pred[l_msk.flatten(), :] = _predict_tree_class(
x[l_msk.flatten(), :], node, node_content_num,
n_classes=n_classes, rights=0, depth=depth + 1)
pred[~l_msk.flatten(), :] = _predict_tree_class(
x[~l_msk.flatten(), :], node, node_content_num,
n_classes=n_classes, rights=1, depth=depth + 1)
return pred
else:
pred = np.empty((x.shape[0],), dtype=np.float64)
l_msk = (x[:, node_content.get().index:
(node_content.get().index + 1)] <=
node_content.get().value)
pred[l_msk.flatten()] = _predict_tree_class(
x[l_msk.flatten()], node, node_content_num,
n_classes=n_classes, rights=0, depth=depth + 1)
pred[~l_msk.flatten()] = _predict_tree_class(
x[~l_msk.flatten()], node, node_content_num,
n_classes=n_classes, rights=1, depth=depth + 1)
return pred
elif isinstance(node_content, _ClassificationNode):
if len(x) > 0:
sk_tree_pred = node_content.content.sk_tree.predict(x)
b = np.zeros((sk_tree_pred.size, n_classes))
b[np.arange(sk_tree_pred.size), sk_tree_pred] = 1
sk_tree_pred = b
pred = np.zeros((len(x), n_classes), dtype=np.float64)
pred[:, np.arange(n_classes)] = sk_tree_pred
return pred
elif isinstance(node_content, _RegressionNode):
if len(x) > 0:
sk_tree_pred = node_content.content.sk_tree.predict(x)
return sk_tree_pred
assert len(x) == 0, "Type not supported"
if n_classes is not None:
return np.empty((0, n_classes), dtype=np.float64)
else:
return np.empty((0,), dtype=np.float64)
@constraint(computing_units="${ComputingUnits}")
@task(x=COLLECTION_IN, node=COLLECTION_IN, returns=1)
def _predict_proba_tree(x, node, node_content_num, n_classes=None,
rights=0, depth=0):
if node_content_num == 0:
node_content_num = node_content_num + 1
else:
node_content_num = node_content_num * 2 + rights
x = np.block(x)
node_content = node[node_content_num - 1]
if len(x) == 0:
return np.empty((0, n_classes), dtype=np.float64)
if isinstance(node_content, _NodeInfo):
if isinstance(node_content.get(), _LeafInfo):
single_pred = (node_content.get().frequencies /
node_content.get().size)
return np.tile(single_pred, (len(x), 1))
elif isinstance(node_content.get(), _InnerNodeInfo):
pred = np.empty((x.shape[0], n_classes), dtype=np.float64)
l_msk = (x[:, node_content.get().index:
(node_content.get().index + 1)] <=
node_content.get().value)
pred[l_msk.flatten(), :] = _predict_proba_tree(
x[l_msk.flatten(), :], node, node_content_num,
n_classes=n_classes, rights=0, depth=depth + 1)
pred[~l_msk.flatten(), :] = _predict_proba_tree(
x[~l_msk.flatten(), :], node, node_content_num,
n_classes=n_classes, rights=1, depth=depth + 1)
return pred
elif isinstance(node_content, _ClassificationNode):
if len(x) > 0:
sk_tree_pred = node_content.content.sk_tree.predict_proba(x)
pred = np.zeros((len(x), n_classes), dtype=np.float64)
pred[:, node_content.content.sk_tree.classes_] = sk_tree_pred
return pred
assert len(x) == 0, "Type not supported"
return np.empty((0, n_classes), dtype=np.float64)
@constraint(computing_units="${ComputingUnits}")
@on_failure(management="CANCEL_SUCCESSORS", returns=0, node_info=[None])
@task(found_solution=INOUT, node_info=INOUT,
rights_x=COLLECTION_INOUT, rights_y=COLLECTION_INOUT,
lefts_x=COLLECTION_INOUT, lefts_y=COLLECTION_INOUT, returns=1)
def evaluate_exception(found_solution, node_info, rights_x,
rights_y, lefts_x, lefts_y):
if found_solution[0] == 1:
raise Exception("Leaf Node")
else:
return None
@constraint(computing_units="${ComputingUnits}")
@task(node_info=INOUT, found_solution=INOUT, y_r=COLLECTION_IN,
y_r_occ=COLLECTION_IN, y_l=COLLECTION_IN, y_l_occ=COLLECTION_IN,
indexes_to_try=COLLECTION_IN)
def generate_nodes_with_data_compressed_regression(node_info, found_solution,
y_r, y_r_occ, y_l, y_l_occ,
attribute_to_split,
indexes_to_try,
optimal_split_point):
if (np.sum(y_l_occ) + np.sum(y_r_occ)) <= 4 or np.sum(y_r_occ) == 0 or\
np.sum(y_l_occ) == 0 or attribute_to_split is None:
node_info.set(_compute_leaf_info((np.sum(y_l) + np.sum(y_r)) /
(np.sum(y_l_occ) + np.sum(y_r_occ)),
None,
occurrences=np.sum(y_l_occ) +
np.sum(y_r_occ)))
found_solution[0] = 1
else:
node_info.set(_InnerNodeInfo(indexes_to_try[attribute_to_split],
optimal_split_point))
found_solution[0] = 0
@constraint(computing_units="${ComputingUnits}")
@task(node_info=INOUT, found_solution=INOUT, y_r=COLLECTION_IN,
y_l=COLLECTION_IN, indexes_to_try=COLLECTION_IN)
def generate_nodes_with_data_compressed(node_info, found_solution, y_r, y_l,
n_classes,
attribute_to_split,
indexes_to_try, optimal_split_point):
data_compressed_left = np.zeros(len(y_l[0]))
for data in y_l:
data_compressed_left += data
data_compressed_right = np.zeros(len(y_r[0]))
for data in y_r:
data_compressed_right += data
if (np.sum(data_compressed_left) + np.sum(data_compressed_right)) <= 4 or\
np.sum(data_compressed_right) == 0 or \
np.sum(data_compressed_left) == 0 or \
attribute_to_split is None:
node_info.set(_compute_leaf_info(data_compressed_left +
data_compressed_right, n_classes))
found_solution[0] = 1
else:
node_info.set(_InnerNodeInfo(indexes_to_try[attribute_to_split],
optimal_split_point))
found_solution[0] = 0
@constraint(computing_units="${ComputingUnits}")
@task(x_block=COLLECTION_IN, y_block=COLLECTION_IN, returns=8)
def apply_split_points_to_blocks_regression(x_block, y_block, best_attribute,
optimal_value, indexes_to_try):
if optimal_value is None:
data_to_compress = np.block(y_block)
len_compress_l = np.array([0])
compress_l = np.array([0])
if len(data_to_compress) > 0:
compress_l = np.sum(data_to_compress)
len_compress_l = len(data_to_compress)
return (None, None, np.block(x_block), np.block(y_block),
np.array([0]), np.array([0]), compress_l, len_compress_l)
if x_block is None:
return (None, None, None, None, np.array([np.nan]),
np.array([np.nan]), np.array([np.nan]), np.array([np.nan]))
else:
x_block = np.block(x_block)
y_block = np.block(y_block)
left_x = x_block[x_block[:,
indexes_to_try[best_attribute]] < optimal_value]
right_x = x_block[x_block[:,
indexes_to_try[best_attribute]] >= optimal_value]
right_y = y_block[x_block[:,
indexes_to_try[best_attribute]] >= optimal_value]
left_y = y_block[x_block[:,
indexes_to_try[best_attribute]] < optimal_value]
data_to_compress = np.block(right_y)
data_to_compress_2 = np.block(left_y)
if len(data_to_compress) > 0:
compress_r = np.sum(data_to_compress)
len_compress_r = len(data_to_compress)
else:
compress_r = np.array([0])
len_compress_r = np.array([0])
if len(data_to_compress_2) > 0:
compress_l = np.sum(data_to_compress_2)
len_compress_l = len(data_to_compress_2)
else:
compress_l = np.array([0])
len_compress_l = np.array([0])
del x_block
del y_block
return (right_x, right_y, left_x, left_y, compress_r,