forked from ukosuagwu/scikit-learn
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_tree.py
More file actions
2392 lines (1920 loc) · 80.4 KB
/
Copy pathtest_tree.py
File metadata and controls
2392 lines (1920 loc) · 80.4 KB
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
"""
Testing for the tree module (sklearn.tree).
"""
import copy
import pickle
from itertools import product, chain
import struct
import io
import copyreg
import pytest
import numpy as np
from numpy.testing import assert_allclose
from scipy.sparse import csc_matrix
from scipy.sparse import csr_matrix
from scipy.sparse import coo_matrix
import joblib
from joblib.numpy_pickle import NumpyPickler
from sklearn.random_projection import _sparse_random_matrix
from sklearn.dummy import DummyRegressor
from sklearn.metrics import accuracy_score
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_poisson_deviance
from sklearn.model_selection import train_test_split
from sklearn.utils._testing import assert_array_equal
from sklearn.utils._testing import assert_array_almost_equal
from sklearn.utils._testing import assert_almost_equal
from sklearn.utils._testing import create_memmap_backed_data
from sklearn.utils._testing import ignore_warnings
from sklearn.utils._testing import skip_if_32bit
from sklearn.utils.estimator_checks import check_sample_weights_invariance
from sklearn.utils.validation import check_random_state
from sklearn.utils import _IS_32BIT
from sklearn.exceptions import NotFittedError
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import DecisionTreeRegressor
from sklearn.tree import ExtraTreeClassifier
from sklearn.tree import ExtraTreeRegressor
from sklearn import tree
from sklearn.tree._tree import TREE_LEAF, TREE_UNDEFINED
from sklearn.tree._tree import Tree as CythonTree
from sklearn.tree._tree import _check_n_classes
from sklearn.tree._tree import _check_value_ndarray
from sklearn.tree._tree import _check_node_ndarray
from sklearn.tree._tree import NODE_DTYPE
from sklearn.tree._classes import CRITERIA_CLF
from sklearn.tree._classes import CRITERIA_REG
from sklearn import datasets
from sklearn.utils import compute_sample_weight
from sklearn.tree._classes import DENSE_SPLITTERS, SPARSE_SPLITTERS
CLF_CRITERIONS = ("gini", "log_loss")
REG_CRITERIONS = ("squared_error", "absolute_error", "friedman_mse", "poisson")
CLF_TREES = {
"DecisionTreeClassifier": DecisionTreeClassifier,
"ExtraTreeClassifier": ExtraTreeClassifier,
}
REG_TREES = {
"DecisionTreeRegressor": DecisionTreeRegressor,
"ExtraTreeRegressor": ExtraTreeRegressor,
}
ALL_TREES: dict = dict()
ALL_TREES.update(CLF_TREES)
ALL_TREES.update(REG_TREES)
SPARSE_TREES = [
"DecisionTreeClassifier",
"DecisionTreeRegressor",
"ExtraTreeClassifier",
"ExtraTreeRegressor",
]
X_small = np.array(
[
[0, 0, 4, 0, 0, 0, 1, -14, 0, -4, 0, 0, 0, 0],
[0, 0, 5, 3, 0, -4, 0, 0, 1, -5, 0.2, 0, 4, 1],
[-1, -1, 0, 0, -4.5, 0, 0, 2.1, 1, 0, 0, -4.5, 0, 1],
[-1, -1, 0, -1.2, 0, 0, 0, 0, 0, 0, 0.2, 0, 0, 1],
[-1, -1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 1],
[-1, -2, 0, 4, -3, 10, 4, 0, -3.2, 0, 4, 3, -4, 1],
[2.11, 0, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0.5, 0, -3, 1],
[2.11, 0, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0, 0, -2, 1],
[2.11, 8, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0, 0, -2, 1],
[2.11, 8, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0.5, 0, -1, 0],
[2, 8, 5, 1, 0.5, -4, 10, 0, 1, -5, 3, 0, 2, 0],
[2, 0, 1, 1, 1, -1, 1, 0, 0, -2, 3, 0, 1, 0],
[2, 0, 1, 2, 3, -1, 10, 2, 0, -1, 1, 2, 2, 0],
[1, 1, 0, 2, 2, -1, 1, 2, 0, -5, 1, 2, 3, 0],
[3, 1, 0, 3, 0, -4, 10, 0, 1, -5, 3, 0, 3, 1],
[2.11, 8, -6, -0.5, 0, 1, 0, 0, -3.2, 6, 0.5, 0, -3, 1],
[2.11, 8, -6, -0.5, 0, 1, 0, 0, -3.2, 6, 1.5, 1, -1, -1],
[2.11, 8, -6, -0.5, 0, 10, 0, 0, -3.2, 6, 0.5, 0, -1, -1],
[2, 0, 5, 1, 0.5, -2, 10, 0, 1, -5, 3, 1, 0, -1],
[2, 0, 1, 1, 1, -2, 1, 0, 0, -2, 0, 0, 0, 1],
[2, 1, 1, 1, 2, -1, 10, 2, 0, -1, 0, 2, 1, 1],
[1, 1, 0, 0, 1, -3, 1, 2, 0, -5, 1, 2, 1, 1],
[3, 1, 0, 1, 0, -4, 1, 0, 1, -2, 0, 0, 1, 0],
]
)
y_small = [1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0]
y_small_reg = [
1.0,
2.1,
1.2,
0.05,
10,
2.4,
3.1,
1.01,
0.01,
2.98,
3.1,
1.1,
0.0,
1.2,
2,
11,
0,
0,
4.5,
0.201,
1.06,
0.9,
0,
]
# toy sample
X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]
y = [-1, -1, -1, 1, 1, 1]
T = [[-1, -1], [2, 2], [3, 2]]
true_result = [-1, 1, 1]
# also load the iris dataset
# and randomly permute it
iris = datasets.load_iris()
rng = np.random.RandomState(1)
perm = rng.permutation(iris.target.size)
iris.data = iris.data[perm]
iris.target = iris.target[perm]
# also load the diabetes dataset
# and randomly permute it
diabetes = datasets.load_diabetes()
perm = rng.permutation(diabetes.target.size)
diabetes.data = diabetes.data[perm]
diabetes.target = diabetes.target[perm]
digits = datasets.load_digits()
perm = rng.permutation(digits.target.size)
digits.data = digits.data[perm]
digits.target = digits.target[perm]
random_state = check_random_state(0)
X_multilabel, y_multilabel = datasets.make_multilabel_classification(
random_state=0, n_samples=30, n_features=10
)
# NB: despite their names X_sparse_* are numpy arrays (and not sparse matrices)
X_sparse_pos = random_state.uniform(size=(20, 5))
X_sparse_pos[X_sparse_pos <= 0.8] = 0.0
y_random = random_state.randint(0, 4, size=(20,))
X_sparse_mix = _sparse_random_matrix(20, 10, density=0.25, random_state=0).toarray()
DATASETS = {
"iris": {"X": iris.data, "y": iris.target},
"diabetes": {"X": diabetes.data, "y": diabetes.target},
"digits": {"X": digits.data, "y": digits.target},
"toy": {"X": X, "y": y},
"clf_small": {"X": X_small, "y": y_small},
"reg_small": {"X": X_small, "y": y_small_reg},
"multilabel": {"X": X_multilabel, "y": y_multilabel},
"sparse-pos": {"X": X_sparse_pos, "y": y_random},
"sparse-neg": {"X": -X_sparse_pos, "y": y_random},
"sparse-mix": {"X": X_sparse_mix, "y": y_random},
"zeros": {"X": np.zeros((20, 3)), "y": y_random},
}
for name in DATASETS:
DATASETS[name]["X_sparse"] = csc_matrix(DATASETS[name]["X"])
def assert_tree_equal(d, s, message):
assert (
s.node_count == d.node_count
), "{0}: inequal number of node ({1} != {2})".format(
message, s.node_count, d.node_count
)
assert_array_equal(
d.children_right, s.children_right, message + ": inequal children_right"
)
assert_array_equal(
d.children_left, s.children_left, message + ": inequal children_left"
)
external = d.children_right == TREE_LEAF
internal = np.logical_not(external)
assert_array_equal(
d.feature[internal], s.feature[internal], message + ": inequal features"
)
assert_array_equal(
d.threshold[internal], s.threshold[internal], message + ": inequal threshold"
)
assert_array_equal(
d.n_node_samples.sum(),
s.n_node_samples.sum(),
message + ": inequal sum(n_node_samples)",
)
assert_array_equal(
d.n_node_samples, s.n_node_samples, message + ": inequal n_node_samples"
)
assert_almost_equal(d.impurity, s.impurity, err_msg=message + ": inequal impurity")
assert_array_almost_equal(
d.value[external], s.value[external], err_msg=message + ": inequal value"
)
def test_classification_toy():
# Check classification on a toy dataset.
for name, Tree in CLF_TREES.items():
clf = Tree(random_state=0)
clf.fit(X, y)
assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name))
clf = Tree(max_features=1, random_state=1)
clf.fit(X, y)
assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name))
def test_weighted_classification_toy():
# Check classification on a weighted toy dataset.
for name, Tree in CLF_TREES.items():
clf = Tree(random_state=0)
clf.fit(X, y, sample_weight=np.ones(len(X)))
assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name))
clf.fit(X, y, sample_weight=np.full(len(X), 0.5))
assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name))
@pytest.mark.parametrize("Tree", REG_TREES.values())
@pytest.mark.parametrize("criterion", REG_CRITERIONS)
def test_regression_toy(Tree, criterion):
# Check regression on a toy dataset.
if criterion == "poisson":
# make target positive while not touching the original y and
# true_result
a = np.abs(np.min(y)) + 1
y_train = np.array(y) + a
y_test = np.array(true_result) + a
else:
y_train = y
y_test = true_result
reg = Tree(criterion=criterion, random_state=1)
reg.fit(X, y_train)
assert_allclose(reg.predict(T), y_test)
clf = Tree(criterion=criterion, max_features=1, random_state=1)
clf.fit(X, y_train)
assert_allclose(reg.predict(T), y_test)
def test_xor():
# Check on a XOR problem
y = np.zeros((10, 10))
y[:5, :5] = 1
y[5:, 5:] = 1
gridx, gridy = np.indices(y.shape)
X = np.vstack([gridx.ravel(), gridy.ravel()]).T
y = y.ravel()
for name, Tree in CLF_TREES.items():
clf = Tree(random_state=0)
clf.fit(X, y)
assert clf.score(X, y) == 1.0, "Failed with {0}".format(name)
clf = Tree(random_state=0, max_features=1)
clf.fit(X, y)
assert clf.score(X, y) == 1.0, "Failed with {0}".format(name)
def test_iris():
# Check consistency on dataset iris.
for (name, Tree), criterion in product(CLF_TREES.items(), CLF_CRITERIONS):
clf = Tree(criterion=criterion, random_state=0)
clf.fit(iris.data, iris.target)
score = accuracy_score(clf.predict(iris.data), iris.target)
assert score > 0.9, "Failed with {0}, criterion = {1} and score = {2}".format(
name, criterion, score
)
clf = Tree(criterion=criterion, max_features=2, random_state=0)
clf.fit(iris.data, iris.target)
score = accuracy_score(clf.predict(iris.data), iris.target)
assert score > 0.5, "Failed with {0}, criterion = {1} and score = {2}".format(
name, criterion, score
)
@pytest.mark.parametrize("name, Tree", REG_TREES.items())
@pytest.mark.parametrize("criterion", REG_CRITERIONS)
def test_diabetes_overfit(name, Tree, criterion):
# check consistency of overfitted trees on the diabetes dataset
# since the trees will overfit, we expect an MSE of 0
reg = Tree(criterion=criterion, random_state=0)
reg.fit(diabetes.data, diabetes.target)
score = mean_squared_error(diabetes.target, reg.predict(diabetes.data))
assert score == pytest.approx(
0
), f"Failed with {name}, criterion = {criterion} and score = {score}"
@skip_if_32bit
@pytest.mark.parametrize("name, Tree", REG_TREES.items())
@pytest.mark.parametrize(
"criterion, max_depth, metric, max_loss",
[
("squared_error", 15, mean_squared_error, 60),
("absolute_error", 20, mean_squared_error, 60),
("friedman_mse", 15, mean_squared_error, 60),
("poisson", 15, mean_poisson_deviance, 30),
],
)
def test_diabetes_underfit(name, Tree, criterion, max_depth, metric, max_loss):
# check consistency of trees when the depth and the number of features are
# limited
reg = Tree(criterion=criterion, max_depth=max_depth, max_features=6, random_state=0)
reg.fit(diabetes.data, diabetes.target)
loss = metric(diabetes.target, reg.predict(diabetes.data))
assert 0 < loss < max_loss
def test_probability():
# Predict probabilities using DecisionTreeClassifier.
for name, Tree in CLF_TREES.items():
clf = Tree(max_depth=1, max_features=1, random_state=42)
clf.fit(iris.data, iris.target)
prob_predict = clf.predict_proba(iris.data)
assert_array_almost_equal(
np.sum(prob_predict, 1),
np.ones(iris.data.shape[0]),
err_msg="Failed with {0}".format(name),
)
assert_array_equal(
np.argmax(prob_predict, 1),
clf.predict(iris.data),
err_msg="Failed with {0}".format(name),
)
assert_almost_equal(
clf.predict_proba(iris.data),
np.exp(clf.predict_log_proba(iris.data)),
8,
err_msg="Failed with {0}".format(name),
)
def test_arrayrepr():
# Check the array representation.
# Check resize
X = np.arange(10000)[:, np.newaxis]
y = np.arange(10000)
for name, Tree in REG_TREES.items():
reg = Tree(max_depth=None, random_state=0)
reg.fit(X, y)
def test_pure_set():
# Check when y is pure.
X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]
y = [1, 1, 1, 1, 1, 1]
for name, TreeClassifier in CLF_TREES.items():
clf = TreeClassifier(random_state=0)
clf.fit(X, y)
assert_array_equal(clf.predict(X), y, err_msg="Failed with {0}".format(name))
for name, TreeRegressor in REG_TREES.items():
reg = TreeRegressor(random_state=0)
reg.fit(X, y)
assert_almost_equal(reg.predict(X), y, err_msg="Failed with {0}".format(name))
def test_numerical_stability():
# Check numerical stability.
X = np.array(
[
[152.08097839, 140.40744019, 129.75102234, 159.90493774],
[142.50700378, 135.81935120, 117.82884979, 162.75781250],
[127.28772736, 140.40744019, 129.75102234, 159.90493774],
[132.37025452, 143.71923828, 138.35694885, 157.84558105],
[103.10237122, 143.71928406, 138.35696411, 157.84559631],
[127.71276855, 143.71923828, 138.35694885, 157.84558105],
[120.91514587, 140.40744019, 129.75102234, 159.90493774],
]
)
y = np.array([1.0, 0.70209277, 0.53896582, 0.0, 0.90914464, 0.48026916, 0.49622521])
with np.errstate(all="raise"):
for name, Tree in REG_TREES.items():
reg = Tree(random_state=0)
reg.fit(X, y)
reg.fit(X, -y)
reg.fit(-X, y)
reg.fit(-X, -y)
def test_importances():
# Check variable importances.
X, y = datasets.make_classification(
n_samples=5000,
n_features=10,
n_informative=3,
n_redundant=0,
n_repeated=0,
shuffle=False,
random_state=0,
)
for name, Tree in CLF_TREES.items():
clf = Tree(random_state=0)
clf.fit(X, y)
importances = clf.feature_importances_
n_important = np.sum(importances > 0.1)
assert importances.shape[0] == 10, "Failed with {0}".format(name)
assert n_important == 3, "Failed with {0}".format(name)
# Check on iris that importances are the same for all builders
clf = DecisionTreeClassifier(random_state=0)
clf.fit(iris.data, iris.target)
clf2 = DecisionTreeClassifier(random_state=0, max_leaf_nodes=len(iris.data))
clf2.fit(iris.data, iris.target)
assert_array_equal(clf.feature_importances_, clf2.feature_importances_)
def test_importances_raises():
# Check if variable importance before fit raises ValueError.
clf = DecisionTreeClassifier()
with pytest.raises(ValueError):
getattr(clf, "feature_importances_")
def test_importances_gini_equal_squared_error():
# Check that gini is equivalent to squared_error for binary output variable
X, y = datasets.make_classification(
n_samples=2000,
n_features=10,
n_informative=3,
n_redundant=0,
n_repeated=0,
shuffle=False,
random_state=0,
)
# The gini index and the mean square error (variance) might differ due
# to numerical instability. Since those instabilities mainly occurs at
# high tree depth, we restrict this maximal depth.
clf = DecisionTreeClassifier(criterion="gini", max_depth=5, random_state=0).fit(
X, y
)
reg = DecisionTreeRegressor(
criterion="squared_error", max_depth=5, random_state=0
).fit(X, y)
assert_almost_equal(clf.feature_importances_, reg.feature_importances_)
assert_array_equal(clf.tree_.feature, reg.tree_.feature)
assert_array_equal(clf.tree_.children_left, reg.tree_.children_left)
assert_array_equal(clf.tree_.children_right, reg.tree_.children_right)
assert_array_equal(clf.tree_.n_node_samples, reg.tree_.n_node_samples)
# TODO(1.3): Remove warning filter
@pytest.mark.filterwarnings("ignore:`max_features='auto'` has been deprecated in 1.1")
def test_max_features():
# Check max_features.
for name, TreeRegressor in REG_TREES.items():
reg = TreeRegressor(max_features="auto")
reg.fit(diabetes.data, diabetes.target)
assert reg.max_features_ == diabetes.data.shape[1]
for name, TreeClassifier in CLF_TREES.items():
clf = TreeClassifier(max_features="auto")
clf.fit(iris.data, iris.target)
assert clf.max_features_ == 2
for name, TreeEstimator in ALL_TREES.items():
est = TreeEstimator(max_features="sqrt")
est.fit(iris.data, iris.target)
assert est.max_features_ == int(np.sqrt(iris.data.shape[1]))
est = TreeEstimator(max_features="log2")
est.fit(iris.data, iris.target)
assert est.max_features_ == int(np.log2(iris.data.shape[1]))
est = TreeEstimator(max_features=1)
est.fit(iris.data, iris.target)
assert est.max_features_ == 1
est = TreeEstimator(max_features=3)
est.fit(iris.data, iris.target)
assert est.max_features_ == 3
est = TreeEstimator(max_features=0.01)
est.fit(iris.data, iris.target)
assert est.max_features_ == 1
est = TreeEstimator(max_features=0.5)
est.fit(iris.data, iris.target)
assert est.max_features_ == int(0.5 * iris.data.shape[1])
est = TreeEstimator(max_features=1.0)
est.fit(iris.data, iris.target)
assert est.max_features_ == iris.data.shape[1]
est = TreeEstimator(max_features=None)
est.fit(iris.data, iris.target)
assert est.max_features_ == iris.data.shape[1]
def test_error():
# Test that it gives proper exception on deficient input.
for name, TreeEstimator in CLF_TREES.items():
# predict before fit
est = TreeEstimator()
with pytest.raises(NotFittedError):
est.predict_proba(X)
est.fit(X, y)
X2 = [[-2, -1, 1]] # wrong feature shape for sample
with pytest.raises(ValueError):
est.predict_proba(X2)
# Wrong dimensions
est = TreeEstimator()
y2 = y[:-1]
with pytest.raises(ValueError):
est.fit(X, y2)
# Test with arrays that are non-contiguous.
Xf = np.asfortranarray(X)
est = TreeEstimator()
est.fit(Xf, y)
assert_almost_equal(est.predict(T), true_result)
# predict before fitting
est = TreeEstimator()
with pytest.raises(NotFittedError):
est.predict(T)
# predict on vector with different dims
est.fit(X, y)
t = np.asarray(T)
with pytest.raises(ValueError):
est.predict(t[:, 1:])
# wrong sample shape
Xt = np.array(X).T
est = TreeEstimator()
est.fit(np.dot(X, Xt), y)
with pytest.raises(ValueError):
est.predict(X)
with pytest.raises(ValueError):
est.apply(X)
clf = TreeEstimator()
clf.fit(X, y)
with pytest.raises(ValueError):
clf.predict(Xt)
with pytest.raises(ValueError):
clf.apply(Xt)
# apply before fitting
est = TreeEstimator()
with pytest.raises(NotFittedError):
est.apply(T)
# non positive target for Poisson splitting Criterion
est = DecisionTreeRegressor(criterion="poisson")
with pytest.raises(ValueError, match="y is not positive.*Poisson"):
est.fit([[0, 1, 2]], [0, 0, 0])
with pytest.raises(ValueError, match="Some.*y are negative.*Poisson"):
est.fit([[0, 1, 2]], [5, -0.1, 2])
def test_min_samples_split():
"""Test min_samples_split parameter"""
X = np.asfortranarray(iris.data, dtype=tree._tree.DTYPE)
y = iris.target
# test both DepthFirstTreeBuilder and BestFirstTreeBuilder
# by setting max_leaf_nodes
for max_leaf_nodes, name in product((None, 1000), ALL_TREES.keys()):
TreeEstimator = ALL_TREES[name]
# test for integer parameter
est = TreeEstimator(
min_samples_split=10, max_leaf_nodes=max_leaf_nodes, random_state=0
)
est.fit(X, y)
# count samples on nodes, -1 means it is a leaf
node_samples = est.tree_.n_node_samples[est.tree_.children_left != -1]
assert np.min(node_samples) > 9, "Failed with {0}".format(name)
# test for float parameter
est = TreeEstimator(
min_samples_split=0.2, max_leaf_nodes=max_leaf_nodes, random_state=0
)
est.fit(X, y)
# count samples on nodes, -1 means it is a leaf
node_samples = est.tree_.n_node_samples[est.tree_.children_left != -1]
assert np.min(node_samples) > 9, "Failed with {0}".format(name)
def test_min_samples_leaf():
# Test if leaves contain more than leaf_count training examples
X = np.asfortranarray(iris.data, dtype=tree._tree.DTYPE)
y = iris.target
# test both DepthFirstTreeBuilder and BestFirstTreeBuilder
# by setting max_leaf_nodes
for max_leaf_nodes, name in product((None, 1000), ALL_TREES.keys()):
TreeEstimator = ALL_TREES[name]
# test integer parameter
est = TreeEstimator(
min_samples_leaf=5, max_leaf_nodes=max_leaf_nodes, random_state=0
)
est.fit(X, y)
out = est.tree_.apply(X)
node_counts = np.bincount(out)
# drop inner nodes
leaf_count = node_counts[node_counts != 0]
assert np.min(leaf_count) > 4, "Failed with {0}".format(name)
# test float parameter
est = TreeEstimator(
min_samples_leaf=0.1, max_leaf_nodes=max_leaf_nodes, random_state=0
)
est.fit(X, y)
out = est.tree_.apply(X)
node_counts = np.bincount(out)
# drop inner nodes
leaf_count = node_counts[node_counts != 0]
assert np.min(leaf_count) > 4, "Failed with {0}".format(name)
def check_min_weight_fraction_leaf(name, datasets, sparse=False):
"""Test if leaves contain at least min_weight_fraction_leaf of the
training set"""
if sparse:
X = DATASETS[datasets]["X_sparse"].astype(np.float32)
else:
X = DATASETS[datasets]["X"].astype(np.float32)
y = DATASETS[datasets]["y"]
weights = rng.rand(X.shape[0])
total_weight = np.sum(weights)
TreeEstimator = ALL_TREES[name]
# test both DepthFirstTreeBuilder and BestFirstTreeBuilder
# by setting max_leaf_nodes
for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 6)):
est = TreeEstimator(
min_weight_fraction_leaf=frac, max_leaf_nodes=max_leaf_nodes, random_state=0
)
est.fit(X, y, sample_weight=weights)
if sparse:
out = est.tree_.apply(X.tocsr())
else:
out = est.tree_.apply(X)
node_weights = np.bincount(out, weights=weights)
# drop inner nodes
leaf_weights = node_weights[node_weights != 0]
assert (
np.min(leaf_weights) >= total_weight * est.min_weight_fraction_leaf
), "Failed with {0} min_weight_fraction_leaf={1}".format(
name, est.min_weight_fraction_leaf
)
# test case with no weights passed in
total_weight = X.shape[0]
for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 6)):
est = TreeEstimator(
min_weight_fraction_leaf=frac, max_leaf_nodes=max_leaf_nodes, random_state=0
)
est.fit(X, y)
if sparse:
out = est.tree_.apply(X.tocsr())
else:
out = est.tree_.apply(X)
node_weights = np.bincount(out)
# drop inner nodes
leaf_weights = node_weights[node_weights != 0]
assert (
np.min(leaf_weights) >= total_weight * est.min_weight_fraction_leaf
), "Failed with {0} min_weight_fraction_leaf={1}".format(
name, est.min_weight_fraction_leaf
)
@pytest.mark.parametrize("name", ALL_TREES)
def test_min_weight_fraction_leaf_on_dense_input(name):
check_min_weight_fraction_leaf(name, "iris")
@pytest.mark.parametrize("name", SPARSE_TREES)
def test_min_weight_fraction_leaf_on_sparse_input(name):
check_min_weight_fraction_leaf(name, "multilabel", True)
def check_min_weight_fraction_leaf_with_min_samples_leaf(name, datasets, sparse=False):
"""Test the interaction between min_weight_fraction_leaf and
min_samples_leaf when sample_weights is not provided in fit."""
if sparse:
X = DATASETS[datasets]["X_sparse"].astype(np.float32)
else:
X = DATASETS[datasets]["X"].astype(np.float32)
y = DATASETS[datasets]["y"]
total_weight = X.shape[0]
TreeEstimator = ALL_TREES[name]
for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 3)):
# test integer min_samples_leaf
est = TreeEstimator(
min_weight_fraction_leaf=frac,
max_leaf_nodes=max_leaf_nodes,
min_samples_leaf=5,
random_state=0,
)
est.fit(X, y)
if sparse:
out = est.tree_.apply(X.tocsr())
else:
out = est.tree_.apply(X)
node_weights = np.bincount(out)
# drop inner nodes
leaf_weights = node_weights[node_weights != 0]
assert np.min(leaf_weights) >= max(
(total_weight * est.min_weight_fraction_leaf), 5
), "Failed with {0} min_weight_fraction_leaf={1}, min_samples_leaf={2}".format(
name, est.min_weight_fraction_leaf, est.min_samples_leaf
)
for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 3)):
# test float min_samples_leaf
est = TreeEstimator(
min_weight_fraction_leaf=frac,
max_leaf_nodes=max_leaf_nodes,
min_samples_leaf=0.1,
random_state=0,
)
est.fit(X, y)
if sparse:
out = est.tree_.apply(X.tocsr())
else:
out = est.tree_.apply(X)
node_weights = np.bincount(out)
# drop inner nodes
leaf_weights = node_weights[node_weights != 0]
assert np.min(leaf_weights) >= max(
(total_weight * est.min_weight_fraction_leaf),
(total_weight * est.min_samples_leaf),
), "Failed with {0} min_weight_fraction_leaf={1}, min_samples_leaf={2}".format(
name, est.min_weight_fraction_leaf, est.min_samples_leaf
)
@pytest.mark.parametrize("name", ALL_TREES)
def test_min_weight_fraction_leaf_with_min_samples_leaf_on_dense_input(name):
check_min_weight_fraction_leaf_with_min_samples_leaf(name, "iris")
@pytest.mark.parametrize("name", SPARSE_TREES)
def test_min_weight_fraction_leaf_with_min_samples_leaf_on_sparse_input(name):
check_min_weight_fraction_leaf_with_min_samples_leaf(name, "multilabel", True)
def test_min_impurity_decrease():
# test if min_impurity_decrease ensure that a split is made only if
# if the impurity decrease is at least that value
X, y = datasets.make_classification(n_samples=10000, random_state=42)
# test both DepthFirstTreeBuilder and BestFirstTreeBuilder
# by setting max_leaf_nodes
for max_leaf_nodes, name in product((None, 1000), ALL_TREES.keys()):
TreeEstimator = ALL_TREES[name]
# Check default value of min_impurity_decrease, 1e-7
est1 = TreeEstimator(max_leaf_nodes=max_leaf_nodes, random_state=0)
# Check with explicit value of 0.05
est2 = TreeEstimator(
max_leaf_nodes=max_leaf_nodes, min_impurity_decrease=0.05, random_state=0
)
# Check with a much lower value of 0.0001
est3 = TreeEstimator(
max_leaf_nodes=max_leaf_nodes, min_impurity_decrease=0.0001, random_state=0
)
# Check with a much lower value of 0.1
est4 = TreeEstimator(
max_leaf_nodes=max_leaf_nodes, min_impurity_decrease=0.1, random_state=0
)
for est, expected_decrease in (
(est1, 1e-7),
(est2, 0.05),
(est3, 0.0001),
(est4, 0.1),
):
assert (
est.min_impurity_decrease <= expected_decrease
), "Failed, min_impurity_decrease = {0} > {1}".format(
est.min_impurity_decrease, expected_decrease
)
est.fit(X, y)
for node in range(est.tree_.node_count):
# If current node is a not leaf node, check if the split was
# justified w.r.t the min_impurity_decrease
if est.tree_.children_left[node] != TREE_LEAF:
imp_parent = est.tree_.impurity[node]
wtd_n_node = est.tree_.weighted_n_node_samples[node]
left = est.tree_.children_left[node]
wtd_n_left = est.tree_.weighted_n_node_samples[left]
imp_left = est.tree_.impurity[left]
wtd_imp_left = wtd_n_left * imp_left
right = est.tree_.children_right[node]
wtd_n_right = est.tree_.weighted_n_node_samples[right]
imp_right = est.tree_.impurity[right]
wtd_imp_right = wtd_n_right * imp_right
wtd_avg_left_right_imp = wtd_imp_right + wtd_imp_left
wtd_avg_left_right_imp /= wtd_n_node
fractional_node_weight = (
est.tree_.weighted_n_node_samples[node] / X.shape[0]
)
actual_decrease = fractional_node_weight * (
imp_parent - wtd_avg_left_right_imp
)
assert (
actual_decrease >= expected_decrease
), "Failed with {0} expected min_impurity_decrease={1}".format(
actual_decrease, expected_decrease
)
def test_pickle():
"""Test pickling preserves Tree properties and performance."""
for name, TreeEstimator in ALL_TREES.items():
if "Classifier" in name:
X, y = iris.data, iris.target
else:
X, y = diabetes.data, diabetes.target
est = TreeEstimator(random_state=0)
est.fit(X, y)
score = est.score(X, y)
# test that all class properties are maintained
attributes = [
"max_depth",
"node_count",
"capacity",
"n_classes",
"children_left",
"children_right",
"n_leaves",
"feature",
"threshold",
"impurity",
"n_node_samples",
"weighted_n_node_samples",
"value",
]
fitted_attribute = {
attribute: getattr(est.tree_, attribute) for attribute in attributes
}
serialized_object = pickle.dumps(est)
est2 = pickle.loads(serialized_object)
assert type(est2) == est.__class__
score2 = est2.score(X, y)
assert (
score == score2
), "Failed to generate same score after pickling with {0}".format(name)
for attribute in fitted_attribute:
assert_array_equal(
getattr(est2.tree_, attribute),
fitted_attribute[attribute],
err_msg=(
f"Failed to generate same attribute {attribute} after pickling with"
f" {name}"
),
)
def test_multioutput():
# Check estimators on multi-output problems.
X = [
[-2, -1],
[-1, -1],
[-1, -2],
[1, 1],
[1, 2],
[2, 1],
[-2, 1],
[-1, 1],
[-1, 2],
[2, -1],
[1, -1],
[1, -2],
]
y = [
[-1, 0],
[-1, 0],
[-1, 0],
[1, 1],
[1, 1],
[1, 1],
[-1, 2],
[-1, 2],
[-1, 2],
[1, 3],
[1, 3],
[1, 3],
]
T = [[-1, -1], [1, 1], [-1, 1], [1, -1]]
y_true = [[-1, 0], [1, 1], [-1, 2], [1, 3]]
# toy classification problem
for name, TreeClassifier in CLF_TREES.items():
clf = TreeClassifier(random_state=0)
y_hat = clf.fit(X, y).predict(T)
assert_array_equal(y_hat, y_true)
assert y_hat.shape == (4, 2)
proba = clf.predict_proba(T)
assert len(proba) == 2
assert proba[0].shape == (4, 2)
assert proba[1].shape == (4, 4)
log_proba = clf.predict_log_proba(T)
assert len(log_proba) == 2
assert log_proba[0].shape == (4, 2)
assert log_proba[1].shape == (4, 4)
# toy regression problem