-
Notifications
You must be signed in to change notification settings - Fork 8
/
_lcetree.py
1073 lines (897 loc) · 51.1 KB
/
_lcetree.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 numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from ._xgboost import xgb_opt_classifier, xgb_opt_regressor
class LCETreeClassifier(ClassifierMixin, BaseEstimator):
"""
A LCE Tree classifier.
Parameters
----------
n_classes_in : int, default=None
The number of classes from the input data.
criterion : {"gini", "entropy"}, default="gini"
The function to measure the quality of a split. Supported criteria are
"gini" for the Gini impurity and "entropy" for the information gain.
splitter : {"best", "random"}, default="best"
The strategy used to choose the split at each node. Supported strategies
are "best" to choose the best split and "random" to choose the best random
split.
max_depth : int, default=2
The maximum depth of a tree.
max_features : int, float or {"auto", "sqrt", "log"}, default=None
The number of features to consider when looking for the best split:
- If int, then consider `max_features` features at each split.
- If float, then `max_features` is a fraction and
`round(max_features * n_features)` features are considered at each
split.
- If "auto", then `max_features=sqrt(n_features)`.
- If "sqrt", then `max_features=sqrt(n_features)` (same as "auto").
- If "log2", then `max_features=log2(n_features)`.
- If None, then `max_features=n_features`.
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 ``max_features`` features.
min_samples_leaf : int or float, default=5
The minimum number of samples required to be at a leaf node.
A split point at any depth will only be considered if it leaves at
least ``min_samples_leaf`` training samples in each of the left and
right branches.
- If int, then consider `min_samples_leaf` as the minimum number.
- If float, then `min_samples_leaf` is a fraction and
`ceil(min_samples_leaf * n_samples)` are the minimum
number of samples for each node.
n_iter: int, default=10
Number of iterations to set the hyperparameters of each node base
classifier in Hyperopt.
metric: string, default="accuracy"
The score of the base classifier (XGBoost) optimized by Hyperopt. Supported metrics
are the ones from `scikit-learn <https://scikit-learn.org/stable/modules/model_evaluation.html>`_.
xgb_max_n_estimators : int, default=100
The maximum number of XGBoost estimators. The number of estimators of
XGBoost corresponds to the number of boosting rounds.
xgb_n_estimators_step : int, default=10
Spacing between XGBoost n_estimators. The range of XGBoost n_estimators
for hyperparameter optimization (Hyperopt) is:
range(1, xgb_max_n_estimators+xgb_n_estimators_step, xgb_n_estimators_step).
xgb_max_depth : int, default=10
Maximum tree depth for XGBoost base learners. The range of XGBoost max_depth
for Hyperopt is: range(1, xgb_max_depth+1).
xgb_min_learning_rate : float, default=0.05
Minimum learning rate of XGBoost. The learning rate corresponds to the
step size shrinkage used in update to prevent overfitting. After each
boosting step, we can directly get the weights of new features,
and the learning rate shrinks the feature weights to make the boosting
process more conservative.
xgb_max_learning_rate : float, default=0.5
Maximum learning rate of XGBoost.
xgb_learning_rate_step : float, default=0.05
Spacing between XGBoost learning_rate. The range of XGBoost learning_rate
for hyperparameter optimization (Hyperopt) is:
np.arange(xgb_min_learning_rate, xgb_max_learning_rate+xgb_learning_rate_step, xgb_learning_rate_step).
xgb_booster : {"dart", "gblinear", "gbtree"}, default="gbtree"
The type of booster to use. "gbtree" and "dart" use tree based models
while "gblinear" uses linear functions.
xgb_min_gamma : float, default=0.05
Minimum gamma of XGBoost. Gamma corresponds to the minimum loss reduction
required to make a further partition on a leaf node of the tree.
The larger gamma is, the more conservative XGBoost algorithm will be.
xgb_max_gamma : float, default=0.5
Maximum gamma of XGBoost.
xgb_gamma_step : float, default=0.05,
Spacing between XGBoost gamma. The range of XGBoost gamma for hyperparameter
optimization (Hyperopt) is:
np.arange(xgb_min_gamma, xgb_max_gamma+xgb_gamma_step, xgb_gamma_step).
xgb_min_min_child_weight : int, default=3
Minimum min_child_weight of XGBoost. min_child_weight defines the
minimum sum of instance weight (hessian) needed in a child. If the tree
partition step results in a leaf node with the sum of instance weight
less than min_child_weight, then the building process will give up further
partitioning. The larger min_child_weight is, the more conservative XGBoost
algorithm will be.
xgb_max_min_child_weight : int, default=10
Minimum min_child_weight of XGBoost.
xgb_min_child_weight_step : int, default=1,
Spacing between XGBoost min_child_weight. The range of XGBoost min_child_weight
for hyperparameter optimization (Hyperopt) is:
range(xgb_min_min_child_weight, xgb_max_min_child_weight+xgb_min_child_weight_step, xgb_min_child_weight_step).
xgb_subsample : float, default=0.8
XGBoost subsample ratio of the training instances. Setting it to 0.5 means
that XGBoost would randomly sample half of the training data prior to
growing trees. and this will prevent overfitting. Subsampling will occur
once in every boosting iteration.
xgb_colsample_bytree : float, default=0.8
XGBoost subsample ratio of columns when constructing each tree.
Subsampling occurs once for every tree constructed.
xgb_colsample_bylevel : float, default=1.0
XGBoost subsample ratio of columns for each level. Subsampling occurs
once for every new depth level reached in a tree. Columns are subsampled
from the set of columns chosen for the current tree.
xgb_colsample_bynode : float, default=1.0
XGBoost subsample ratio of columns for each node (split). Subsampling
occurs once every time a new split is evaluated. Columns are subsampled
from the set of columns chosen for the current level.
xgb_min_reg_alpha : float, default=0.01
Minimum reg_alpha of XGBoost. reg_alpha corresponds to the L1 regularization
term on the weights. Increasing this value will make XGBoost model more
conservative.
xgb_max_reg_alpha : float, default=0.1
Maximum reg_alpha of XGBoost.
xgb_reg_alpha_step : float, default=0.05
Spacing between XGBoost reg_alpha. The range of XGBoost reg_alpha for
hyperparameter optimization (Hyperopt) is:
np.arange(xgb_min_reg_alpha, xgb_max_reg_alpha+xgb_reg_alpha_step, xgb_reg_alpha_step).
xgb_min_reg_lambda : float, default=0.01
Minimum reg_lambda of XGBoost. reg_lambda corresponds to the L2 regularization
term on the weights. Increasing this value will make XGBoost model more
conservative.
xgb_max_reg_lambda : float, default=0.1
Maximum reg_lambda of XGBoost.
xgb_reg_lambda_step : float, default=0.05
Spacing between XGBoost reg_lambda. The range of XGBoost reg_lambda for
hyperparameter optimization (Hyperopt) is:
np.arange(xgb_min_reg_lambda, xgb_max_reg_lambda+xgb_reg_lambda_step, xgb_reg_lambda_step).
n_jobs : int, default=None
The number of jobs to run in parallel.
``None`` means 1. ``-1`` means using all processors.
random_state : int, RandomState instance or None, default=None
Controls the randomness of the sampling of the features to consider when
looking for the best split at each node (if ``max_features < n_features``),
the base classifier (XGBoost) and the Hyperopt algorithm.
verbose : int, default=0
Controls the verbosity when fitting.
Attributes
----------
classes_ : ndarray of shape (n_classes,) or a list of such arrays
The classes labels.
n_features_in_ : int
The number of features when ``fit`` is performed.
"""
def __init__(self, n_classes_in=None, criterion='gini', splitter='best', max_depth=2,
max_features=None, min_samples_leaf=5, n_iter=10, metric='accuracy',
xgb_max_n_estimators=100, xgb_n_estimators_step=10, xgb_max_depth=10,
xgb_min_learning_rate=0.05, xgb_max_learning_rate=0.5, xgb_learning_rate_step=0.05,
xgb_booster='gbtree', xgb_min_gamma=0.05, xgb_max_gamma=0.5, xgb_gamma_step=0.05,
xgb_min_min_child_weight=3, xgb_max_min_child_weight=10, xgb_min_child_weight_step=1,
xgb_subsample=0.8, xgb_colsample_bytree=0.8,
xgb_colsample_bylevel=1.0, xgb_colsample_bynode=1.0,
xgb_min_reg_alpha=0.01, xgb_max_reg_alpha=0.1, xgb_reg_alpha_step=0.05,
xgb_min_reg_lambda=0.01, xgb_max_reg_lambda=0.1, xgb_reg_lambda_step=0.05,
n_jobs=None, random_state=None, verbose=0):
self.n_classes_in = n_classes_in
self.criterion = criterion
self.splitter = splitter
self.max_depth = max_depth
self.max_features = max_features
self.min_samples_leaf = min_samples_leaf
self.n_iter = n_iter
self.metric = metric
self.xgb_max_n_estimators = xgb_max_n_estimators
self.xgb_n_estimators_step = xgb_n_estimators_step
self.xgb_max_depth = xgb_max_depth
self.xgb_min_learning_rate = xgb_min_learning_rate
self.xgb_max_learning_rate = xgb_max_learning_rate
self.xgb_learning_rate_step = xgb_learning_rate_step
self.xgb_booster = xgb_booster
self.xgb_min_gamma = xgb_min_gamma
self.xgb_max_gamma = xgb_max_gamma
self.xgb_gamma_step = xgb_gamma_step
self.xgb_min_min_child_weight = xgb_min_min_child_weight
self.xgb_max_min_child_weight = xgb_max_min_child_weight
self.xgb_min_child_weight_step = xgb_min_child_weight_step
self.xgb_subsample = xgb_subsample
self.xgb_colsample_bytree = xgb_colsample_bytree
self.xgb_colsample_bylevel = xgb_colsample_bylevel
self.xgb_colsample_bynode = xgb_colsample_bynode
self.xgb_min_reg_alpha = xgb_min_reg_alpha
self.xgb_max_reg_alpha = xgb_max_reg_alpha
self.xgb_reg_alpha_step = xgb_reg_alpha_step
self.xgb_min_reg_lambda = xgb_min_reg_lambda
self.xgb_max_reg_lambda = xgb_max_reg_lambda
self.xgb_reg_lambda_step = xgb_reg_lambda_step
self.n_jobs = n_jobs
self.random_state = random_state
self.verbose = verbose
def fit(self, X, y):
"""
Build a LCE tree from the training set (X, y).
Parameters
----------
X : array-like of shape (n_samples, n_features)
The training input samples.
y : array-like of shape (n_samples,)
The class labels.
Returns
-------
self : object
"""
self.classes_ = np.unique(y)
self.n_features_in_ = X.shape[1]
def _build_tree(X, y):
"""Build a LCE tree."""
global index_node_global
def _create_node(X, y, depth, container):
"""Create a node in the tree."""
# Add XGBoost predictions as features to the dataset
model_node = xgb_opt_classifier(X, y, n_iter=self.n_iter,
metric = self.metric,
n_estimators=self.xgb_max_n_estimators,
n_estimators_step = self.xgb_n_estimators_step,
max_depth=self.xgb_max_depth,
min_learning_rate = self.xgb_min_learning_rate,
max_learning_rate = self.xgb_max_learning_rate,
learning_rate_step = self.xgb_learning_rate_step,
booster = self.xgb_booster,
min_gamma = self.xgb_min_gamma,
max_gamma = self.xgb_max_gamma,
gamma_step = self.xgb_gamma_step,
min_min_child_weight = self.xgb_min_min_child_weight,
max_min_child_weight = self.xgb_max_min_child_weight,
min_child_weight_step = self.xgb_min_child_weight_step,
subsample=self.xgb_subsample,
colsample_bytree = self.xgb_colsample_bytree,
colsample_bylevel = self.xgb_colsample_bylevel,
colsample_bynode = self.xgb_colsample_bynode,
min_reg_alpha = self.xgb_min_reg_alpha,
max_reg_alpha = self.xgb_max_reg_alpha,
reg_alpha_step = self.xgb_reg_alpha_step,
min_reg_lambda = self.xgb_min_reg_lambda,
max_reg_lambda = self.xgb_max_reg_lambda,
reg_lambda_step = self.xgb_reg_lambda_step,
n_jobs = self.n_jobs,
random_state=self.random_state)
pred_proba = np.around(model_node.predict_proba(X), 6)
c = 0
for i in range(0, self.n_classes_in):
X = np.insert(X, X.shape[1], 0, axis=1)
if i in y:
if np.unique(y).size == 1:
X[:, -1] = pred_proba[:, 1]
else:
X[:, -1] = pred_proba[:, c]
c += 1
# Missing data information
num_nans = np.isnan(X).any(axis=1).sum()
if num_nans > 0:
missing = True
if num_nans == y.size:
missing_only = True
else:
missing_only = False
else:
missing = False
missing_only = False
# Split
split_val_conditions = [y.size > 1,
missing_only == False]
if all(split_val_conditions):
split = DecisionTreeClassifier(criterion=self.criterion, splitter=self.splitter,
max_depth=1, max_features=self.max_features,
random_state=self.random_state)
if missing:
nans = np.isnan(X).any(axis=1)
split.fit(X[~nans], y[~nans])
else:
split.fit(X, y)
else:
split = None
# Node information
node = {"index": container["index_node_global"],
"model": model_node,
"data": (X, y),
"classes_in": np.unique(y),
"num_classes": self.n_classes_in,
"split": split,
"missing": {"missing": missing, "missing_only": missing_only},
"missing_side": None,
"children": {"left": None, "right": None},
"depth": depth}
container["index_node_global"] += 1
return node
def _splitter(node):
"""Perform the split of a node."""
# Extract data
X, y = node["data"]
depth = node["depth"]
split = node["split"]
missing = node["missing"]["missing"]
missing_only = node["missing"]["missing_only"]
did_split = False
data = None
# Perform split if the conditions are met
stopping_criteria = [depth >= 0,
depth < self.max_depth,
np.unique(y).size > 1,
missing_only == False]
if all(stopping_criteria):
if missing:
nans = np.isnan(X).any(axis=1)
X_withoutnans, y_withoutnans = X[~nans], y[~nans]
leafs = split.apply(X_withoutnans)
(X_left, y_left), (X_right, y_right) = (np.squeeze(X_withoutnans[np.argwhere(leafs==1), :]), np.squeeze(y_withoutnans[np.argwhere(leafs==1)])), (np.squeeze(X_withoutnans[np.argwhere(leafs==2), :]), np.squeeze(y_withoutnans[np.argwhere(leafs==2)]))
else:
leafs = split.apply(X)
(X_left, y_left), (X_right, y_right) = (np.squeeze(X[np.argwhere(leafs==1), :]), np.squeeze(y[np.argwhere(leafs==1)])), (np.squeeze(X[np.argwhere(leafs==2), :]), np.squeeze(y[np.argwhere(leafs==2)]))
N_left, N_right = y_left.size, y_right.size
split_conditions = [N_left >= self.min_samples_leaf,
N_right >= self.min_samples_leaf]
if all(split_conditions):
did_split = True
if N_left == 1:
X_left = X_left.reshape(-1, 1).T
node["missing_side"] = 'left'
if missing:
X_left = np.append(X_left, X[nans], axis=0)
y_left = np.append([y_left], y[nans], axis=0)
if N_right == 1:
X_right = X_right.reshape(-1, 1).T
if N_left > 1:
node["missing_side"] = 'right'
if missing:
X_right = np.append(X_right, X[nans], axis=0)
y_right = np.append([y_right], y[nans], axis=0)
score_conditions = [N_left > 1,
N_right > 1]
if all(score_conditions):
if split.score(X_left, y_left) > split.score(X_right, y_right):
node["missing_side"] = 'left'
if missing:
X_left = np.append(X_left, X[nans], axis=0)
y_left = np.append(y_left, y[nans], axis=0)
else:
node["missing_side"] = 'right'
if missing:
X_right = np.append(X_right, X[nans], axis=0)
y_right = np.append(y_right, y[nans], axis=0)
data = [(X_left, y_left), (X_right, y_right)]
result = {"did_split": did_split,
"data": data}
return result
def _split_traverse_node(node, container):
"""Process splitting results and continue with child nodes."""
# Perform split and collect result
result = _splitter(node)
# Return terminal node if no split
if not result["did_split"]:
if self.verbose > 0 and self.n_jobs == None:
depth_spacing_str = " ".join([" "] * node["depth"])
print(" {}*leaf {} @ depth {}: Unique_y {}, N_samples {}".format(depth_spacing_str, node["index"], node["depth"], np.unique(node["data"][1]), np.unique(node["data"][1], return_counts=True)[1]))
return
del node["data"]
# Extract splitting results
(X_left, y_left), (X_right, y_right) = result["data"]
# Report created node to user
if self.verbose > 0 and self.n_jobs == None:
depth_spacing_str = " ".join([" "] * node["depth"])
print(" {}node {} @ depth {}: dataset={}, N_left={}, N_right={}".format(depth_spacing_str, node["index"], node["depth"], (X_left.shape[0]+X_right.shape[0], X_left.shape[1]), X_left.shape[0], X_right.shape[0]))
# Create child nodes
node["children"]["left"] = _create_node(X_left, y_left, node["depth"]+1, container)
node["children"]["right"] = _create_node(X_right, y_right, node["depth"]+1, container)
# Split nodes
_split_traverse_node(node["children"]["left"], container)
_split_traverse_node(node["children"]["right"], container)
container = {"index_node_global": 0}
if self.verbose > 0 and self.n_jobs == None:
print('\nNew Tree')
root = _create_node(X, y, 0, container)
_split_traverse_node(root, container)
return root
self.tree = _build_tree(X, y)
return self
def predict_proba(self, X):
"""
Predict class probabilities for X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The training input samples.
Returns
-------
y : ndarray of shape (n_samples,)
The class probabilities of the input samples.
"""
def _base_proba(node, X):
y_pred = np.around(node["model"].predict_proba(X[:, 1:]), 6)
d = 0
for j in range(0, node["num_classes"]):
X = np.insert(X, X.shape[1], 0, axis=1)
if j in node["classes_in"]:
if node["classes_in"].size == 1:
X[:, -1] = y_pred[:, 1]
else:
X[:, -1] = y_pred[:, d]
d += 1
return X
def _predict_proba(node, X, y_pred_final=None):
if X.ndim == 1:
X = _base_proba(node, X.reshape(-1, 1).T)
else:
X = _base_proba(node, X)
no_children = node["children"]["left"] is None and \
node["children"]["right"] is None
if no_children:
y_pred = np.column_stack((X[:, :1], X[:, -node["num_classes"]:]))
if y_pred_final is not None:
y_pred_final = np.concatenate((y_pred_final, y_pred), axis=0)
else:
y_pred_final = y_pred
return y_pred_final
else:
if np.isnan(X).sum() > 0:
nans = np.isnan(X).any(axis=1)
leafs = node["split"].apply(X[~nans, 1:])
X_left, X_right = np.squeeze(X[~nans][np.argwhere(leafs==1), :]), np.squeeze(X[~nans][np.argwhere(leafs==2), :])
if node["missing_side"] == 'left':
X_left, X_right = np.concatenate((X_left, X[nans]), axis=0), X_right
else:
X_left, X_right = X_left, np.concatenate((X_right, X[nans]), axis=0)
else:
leafs = node["split"].apply(X[:, 1:])
X_left, X_right = np.squeeze(X[np.argwhere(leafs==1), :]), np.squeeze(X[np.argwhere(leafs==2), :])
if len(X_left) > 0:
y_pred_final = _predict_proba(node["children"]["left"], X_left, y_pred_final)
if len(X_right) > 0:
y_pred_final = _predict_proba(node["children"]["right"], X_right, y_pred_final)
return y_pred_final
index = np.arange(0, X.shape[0]).reshape(-1, 1)
X = np.concatenate((index, X), axis=1)
y_pred = _predict_proba(self.tree, X, None)
y_pred = y_pred[y_pred[:, 0].argsort()]
y_pred = y_pred[:, 1:]
return y_pred
def set_params(self, **params):
"""
Set the parameters of the estimator.
Parameters
----------
**params : dict
Estimator parameters.
Returns
-------
self : object
"""
if not params:
return self
for key, value in params.items():
if hasattr(self, key):
setattr(self, key, value)
else:
self.kwargs[key] = value
return self
class LCETreeRegressor(RegressorMixin, BaseEstimator):
"""
A LCE Tree regressor.
Parameters
----------
criterion : {"squared_error", "friedman_mse", "absolute_error", "poisson"}, default="squared_error"
The function to measure the quality of a split. Supported criteria are "squared_error" for
the mean squared error, which is equal to variance reduction as feature selection
criterion and minimizes the L2 loss using the mean of each terminal node,
"friedman_mse", which uses mean squared error with Friedman's improvement score
for potential splits, "absolute_error" for the mean absolute error, which
minimizes the L1 loss using the median of each terminal node, and "poisson"
which uses reduction in Poisson deviance to find splits.
splitter : {"best", "random"}, default="best"
The strategy used to choose the split at each node. Supported strategies
are "best" to choose the best split and "random" to choose the best random
split.
max_depth : int, default=2
The maximum depth of a tree.
max_features : int, float or {"auto", "sqrt", "log"}, default=None
The number of features to consider when looking for the best split:
- If int, then consider `max_features` features at each split.
- If float, then `max_features` is a fraction and
`round(max_features * n_features)` features are considered at each
split.
- If "auto", then `max_features=sqrt(n_features)`.
- If "sqrt", then `max_features=sqrt(n_features)` (same as "auto").
- If "log2", then `max_features=log2(n_features)`.
- If None, then `max_features=n_features`.
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 ``max_features`` features.
min_samples_leaf : int or float, default=5
The minimum number of samples required to be at a leaf node.
A split point at any depth will only be considered if it leaves at
least ``min_samples_leaf`` training samples in each of the left and
right branches.
- If int, then consider `min_samples_leaf` as the minimum number.
- If float, then `min_samples_leaf` is a fraction and
`ceil(min_samples_leaf * n_samples)` are the minimum
number of samples for each node.
n_iter: int, default=10
Number of iterations to set the hyperparameters of each node base
regressor (XGBoost) in Hyperopt.
metric: string, default="neg_mean_squared_error"
The score of the base regressor (XGBoost) optimized by Hyperopt. Supported metrics
are the ones from `scikit-learn <https://scikit-learn.org/stable/modules/model_evaluation.html>`_.
xgb_max_n_estimators : int, default=100
The maximum number of XGBoost estimators. The number of estimators of
XGBoost corresponds to the number of boosting rounds.
xgb_n_estimators_step : int, default=10
Spacing between XGBoost n_estimators. The range of XGBoost n_estimators
for hyperparameter optimization (Hyperopt) is:
range(1, xgb_max_n_estimators+xgb_n_estimators_step, xgb_n_estimators_step).
xgb_max_depth : int, default= 10
Maximum tree depth for XGBoost base learners. The range of XGBoost max_depth
for Hyperopt is: range(1, xgb_max_depth+1).
xgb_min_learning_rate : float, default=0.05
Minimum learning rate of XGBoost. The learning rate corresponds to the
step size shrinkage used in update to prevent overfitting. After each
boosting step, we can directly get the weights of new features,
and the learning rate shrinks the feature weights to make the boosting
process more conservative.
xgb_max_learning_rate : float, default=0.5
Maximum learning rate of XGBoost.
xgb_learning_rate_step : float, default=0.05
Spacing between XGBoost learning_rate. The range of XGBoost learning_rate
for hyperparameter optimization (Hyperopt) is:
np.arange(xgb_min_learning_rate, xgb_max_learning_rate+xgb_learning_rate_step, xgb_learning_rate_step).
xgb_booster : {"dart", "gblinear", "gbtree"}, default="gbtree"
The type of booster to use. "gbtree" and "dart" use tree based models
while "gblinear" uses linear functions.
xgb_min_gamma : float, default=0.05
Minimum gamma of XGBoost. Gamma corresponds to the minimum loss reduction
required to make a further partition on a leaf node of the tree.
The larger gamma is, the more conservative XGBoost algorithm will be.
xgb_max_gamma : float, default=0.5
Maximum gamma of XGBoost.
xgb_gamma_step : float, default=0.05,
Spacing between XGBoost gamma. The range of XGBoost gamma for hyperparameter
optimization (Hyperopt) is:
np.arange(xgb_min_gamma, xgb_max_gamma+xgb_gamma_step, xgb_gamma_step).
xgb_min_min_child_weight : int, default=3
Minimum min_child_weight of XGBoost. min_child_weight defines the
minimum sum of instance weight (hessian) needed in a child. If the tree
partition step results in a leaf node with the sum of instance weight
less than min_child_weight, then the building process will give up further
partitioning. The larger min_child_weight is, the more conservative XGBoost
algorithm will be.
xgb_max_min_child_weight : int, default=10
Minimum min_child_weight of XGBoost.
xgb_min_child_weight_step : int, default=1,
Spacing between XGBoost min_child_weight. The range of XGBoost min_child_weight
for hyperparameter optimization (Hyperopt) is:
range(xgb_min_min_child_weight, xgb_max_min_child_weight+xgb_min_child_weight_step, xgb_min_child_weight_step).
xgb_subsample : float, default=0.8
XGBoost subsample ratio of the training instances. Setting it to 0.5 means
that XGBoost would randomly sample half of the training data prior to
growing trees. and this will prevent overfitting. Subsampling will occur
once in every boosting iteration.
xgb_colsample_bytree : float, default=0.8
XGBoost subsample ratio of columns when constructing each tree.
Subsampling occurs once for every tree constructed.
xgb_colsample_bylevel : float, default=1.0
XGBoost subsample ratio of columns for each level. Subsampling occurs
once for every new depth level reached in a tree. Columns are subsampled
from the set of columns chosen for the current tree.
xgb_colsample_bynode : float, default=1.0
XGBoost subsample ratio of columns for each node (split). Subsampling
occurs once every time a new split is evaluated. Columns are subsampled
from the set of columns chosen for the current level.
xgb_min_reg_alpha : float, default=0.01
Minimum reg_alpha of XGBoost. reg_alpha corresponds to the L1 regularization
term on the weights. Increasing this value will make XGBoost model more
conservative.
xgb_max_reg_alpha : float, default=0.1
Maximum reg_alpha of XGBoost.
xgb_reg_alpha_step : float, default=0.05
Spacing between XGBoost reg_alpha. The range of XGBoost reg_alpha for
hyperparameter optimization (Hyperopt) is:
np.arange(xgb_min_reg_alpha, xgb_max_reg_alpha+xgb_reg_alpha_step, xgb_reg_alpha_step).
xgb_min_reg_lambda : float, default=0.01
Minimum reg_lambda of XGBoost. reg_lambda corresponds to the L2 regularization
term on the weights. Increasing this value will make XGBoost model more
conservative.
xgb_max_reg_lambda : float, default=0.1
Maximum reg_lambda of XGBoost.
xgb_reg_lambda_step : float, default=0.05
Spacing between XGBoost reg_lambda. The range of XGBoost reg_lambda for
hyperparameter optimization (Hyperopt) is:
np.arange(xgb_min_reg_lambda, xgb_max_reg_lambda+xgb_reg_lambda_step, xgb_reg_lambda_step).
n_jobs : int, default=None
The number of jobs to run in parallel.
``None`` means 1. ``-1`` means using all processors.
random_state : int, RandomState instance or None, default=None
Controls the randomness of the sampling of the features to consider when
looking for the best split at each node (if ``max_features < n_features``),
the base classifier (XGBoost) and the Hyperopt algorithm.
verbose : int, default=0
Controls the verbosity when fitting.
Attributes
----------
n_features_in_ : int
The number of features when ``fit`` is performed.
"""
def __init__(self, criterion='squared_error', splitter='best', max_depth=2,
max_features=None, min_samples_leaf=5, n_iter=10, metric = 'neg_mean_squared_error',
xgb_max_n_estimators=100, xgb_n_estimators_step=10, xgb_max_depth=10,
xgb_min_learning_rate=0.05, xgb_max_learning_rate=0.5, xgb_learning_rate_step=0.05,
xgb_booster='gbtree', xgb_min_gamma=0.05, xgb_max_gamma=0.5, xgb_gamma_step=0.05,
xgb_min_min_child_weight=3, xgb_max_min_child_weight=10, xgb_min_child_weight_step=1,
xgb_subsample=0.8, xgb_colsample_bytree=0.8,
xgb_colsample_bylevel=1.0, xgb_colsample_bynode=1.0,
xgb_min_reg_alpha=0.01, xgb_max_reg_alpha=0.1, xgb_reg_alpha_step=0.05,
xgb_min_reg_lambda=0.01, xgb_max_reg_lambda=0.1, xgb_reg_lambda_step=0.05,
n_jobs=None, random_state=None, verbose=0):
self.criterion = criterion
self.splitter = splitter
self.max_depth = max_depth
self.max_features = max_features
self.min_samples_leaf = min_samples_leaf
self.n_iter = n_iter
self.metric = metric
self.xgb_max_n_estimators = xgb_max_n_estimators
self.xgb_n_estimators_step = xgb_n_estimators_step
self.xgb_max_depth = xgb_max_depth
self.xgb_min_learning_rate = xgb_min_learning_rate
self.xgb_max_learning_rate = xgb_max_learning_rate
self.xgb_learning_rate_step = xgb_learning_rate_step
self.xgb_booster = xgb_booster
self.xgb_min_gamma = xgb_min_gamma
self.xgb_max_gamma = xgb_max_gamma
self.xgb_gamma_step = xgb_gamma_step
self.xgb_min_min_child_weight = xgb_min_min_child_weight
self.xgb_max_min_child_weight = xgb_max_min_child_weight
self.xgb_min_child_weight_step = xgb_min_child_weight_step
self.xgb_subsample = xgb_subsample
self.xgb_colsample_bytree = xgb_colsample_bytree
self.xgb_colsample_bylevel = xgb_colsample_bylevel
self.xgb_colsample_bynode = xgb_colsample_bynode
self.xgb_min_reg_alpha = xgb_min_reg_alpha
self.xgb_max_reg_alpha = xgb_max_reg_alpha
self.xgb_reg_alpha_step = xgb_reg_alpha_step
self.xgb_min_reg_lambda = xgb_min_reg_lambda
self.xgb_max_reg_lambda = xgb_max_reg_lambda
self.xgb_reg_lambda_step = xgb_reg_lambda_step
self.n_jobs = n_jobs
self.random_state = random_state
self.verbose = verbose
def fit(self, X, y):
"""
Build a LCE tree from the training set (X, y).
Parameters
----------
X : array-like of shape (n_samples, n_features)
The training input samples.
y : array-like of shape (n_samples,)
The target values (real numbers).
Returns
-------
self : object
"""
self.n_features_in_ = X.shape[1]
def _build_tree(X, y):
"""Build a LCE tree."""
global index_node_global
def _create_node(X, y, depth, container):
"""Create a node in the tree."""
# Add XGBoost predictions as features to the dataset
model_node = xgb_opt_regressor(X, y, n_iter=self.n_iter,
metric = self.metric,
n_estimators=self.xgb_max_n_estimators,
n_estimators_step = self.xgb_n_estimators_step,
max_depth=self.xgb_max_depth,
min_learning_rate = self.xgb_min_learning_rate,
max_learning_rate = self.xgb_max_learning_rate,
learning_rate_step = self.xgb_learning_rate_step,
booster = self.xgb_booster,
min_gamma = self.xgb_min_gamma,
max_gamma = self.xgb_max_gamma,
gamma_step = self.xgb_gamma_step,
min_min_child_weight = self.xgb_min_min_child_weight,
max_min_child_weight = self.xgb_max_min_child_weight,
min_child_weight_step = self.xgb_min_child_weight_step,
subsample=self.xgb_subsample,
colsample_bytree = self.xgb_colsample_bytree,
colsample_bylevel = self.xgb_colsample_bylevel,
colsample_bynode = self.xgb_colsample_bynode,
min_reg_alpha = self.xgb_min_reg_alpha,
max_reg_alpha = self.xgb_max_reg_alpha,
reg_alpha_step = self.xgb_reg_alpha_step,
min_reg_lambda = self.xgb_min_reg_lambda,
max_reg_lambda = self.xgb_max_reg_lambda,
reg_lambda_step = self.xgb_reg_lambda_step,
n_jobs = self.n_jobs,
random_state=self.random_state)
preds = np.around(model_node.predict(X), 6)
X = np.insert(X, X.shape[1], 0, axis=1)
X[:, -1] = preds
# Missing data information
num_nans = np.isnan(X).any(axis=1).sum()
if num_nans > 0:
missing = True
if num_nans == y.size:
missing_only = True
else:
missing_only = False
else:
missing = False
missing_only = False
# Split
split_val_conditions = [y.size > 1,
missing_only == False]
if all(split_val_conditions):
split = DecisionTreeRegressor(criterion=self.criterion, splitter=self.splitter,
max_depth=1, max_features=self.max_features,
random_state=self.random_state)
if missing:
nans = np.isnan(X).any(axis=1)
split.fit(X[~nans], y[~nans])
else:
split.fit(X, y)
else:
split = None
# Node information
node = {"index": container["index_node_global"],
"model": model_node,
"data": (X, y),
"split": split,
"missing": {"missing": missing, "missing_only": missing_only},
"missing_side": None,
"children": {"left": None, "right": None},
"depth": depth}
container["index_node_global"] += 1
return node
def _splitter(node):
"""Perform the split of a node."""
# Extract data
X, y = node["data"]
depth = node["depth"]
split = node["split"]
missing = node["missing"]["missing"]
missing_only = node["missing"]["missing_only"]
did_split = False
data = None
# Perform split if the conditions are met
stopping_criteria = [depth >= 0,
depth < self.max_depth,
X[:, 0].size > 1,
missing_only == False]
if all(stopping_criteria):
if missing:
nans = np.isnan(X).any(axis=1)
X_withoutnans, y_withoutnans = X[~nans], y[~nans]
leafs = split.apply(X_withoutnans)
(X_left, y_left), (X_right, y_right) = (np.squeeze(X_withoutnans[np.argwhere(leafs==1), :]), np.squeeze(y_withoutnans[np.argwhere(leafs==1)])), (np.squeeze(X_withoutnans[np.argwhere(leafs==2), :]), np.squeeze(y_withoutnans[np.argwhere(leafs==2)]))
else:
leafs = split.apply(X)
(X_left, y_left), (X_right, y_right) = (np.squeeze(X[np.argwhere(leafs==1), :]), np.squeeze(y[np.argwhere(leafs==1)])), (np.squeeze(X[np.argwhere(leafs==2), :]), np.squeeze(y[np.argwhere(leafs==2)]))
N_left, N_right = y_left.size, y_right.size
split_conditions = [N_left >= self.min_samples_leaf,
N_right >= self.min_samples_leaf]
if all(split_conditions):
did_split = True
if N_left == 1:
X_left = X_left.reshape(-1, 1).T
node["missing_side"] = 'left'
if missing:
X_left = np.append(X_left, X[nans], axis=0)
y_left = np.append([y_left], y[nans], axis=0)
if N_right == 1:
X_right = X_right.reshape(-1, 1).T
if N_left > 1:
node["missing_side"] = 'right'
if missing:
X_right = np.append(X_right, X[nans], axis=0)
y_right = np.append([y_right], y[nans], axis=0)
score_conditions = [N_left > 1,
N_right > 1]
if all(score_conditions):
if split.score(X_left, y_left) > split.score(X_right, y_right):
node["missing_side"] = 'left'
if missing:
X_left = np.append(X_left, X[nans], axis=0)
y_left = np.append(y_left, y[nans], axis=0)
else:
node["missing_side"] = 'right'
if missing:
X_right = np.append(X_right, X[nans], axis=0)
y_right = np.append(y_right, y[nans], axis=0)
data = [(X_left, y_left), (X_right, y_right)]
result = {"did_split": did_split,
"data": data}
return result
def _split_traverse_node(node, container):
"""Process splitting results and continue with child nodes."""
# Perform split and collect result
result = _splitter(node)
# Return terminal node if no split
if not result["did_split"]:
if self.verbose > 0 and self.n_jobs == None:
depth_spacing_str = " ".join([" "] * node["depth"])
print(" {}*leaf {} @ depth {}: Unique_y {}, N_samples {}".format(depth_spacing_str, node["index"], node["depth"], np.unique(node["data"][1]), np.unique(node["data"][1], return_counts=True)[1]))
return
del node["data"]
# Extract splitting results
(X_left, y_left), (X_right, y_right) = result["data"]
# Report created node to user
if self.verbose > 0 and self.n_jobs == None:
depth_spacing_str = " ".join([" "] * node["depth"])
print(" {}node {} @ depth {}: dataset={}, N_left={}, N_right={}".format(depth_spacing_str, node["index"], node["depth"], (X_left.shape[0]+X_right.shape[0], X_left.shape[1]), X_left.shape[0], X_right.shape[0]))
# Create child nodes
node["children"]["left"] = _create_node(X_left, y_left, node["depth"]+1, container)
node["children"]["right"] = _create_node(X_right, y_right, node["depth"]+1, container)
# Split nodes
_split_traverse_node(node["children"]["left"], container)
_split_traverse_node(node["children"]["right"], container)
container = {"index_node_global": 0}
if self.verbose > 0 and self.n_jobs == None:
print('\nNew Tree')
root = _create_node(X, y, 0, container)
_split_traverse_node(root, container)
return root
self.tree = _build_tree(X, y)
return self
def predict(self, X):
"""
Predict regression target for X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The training input samples.
Returns
-------
y : ndarray of shape (n_samples,)
The predicted values.