-
-
Notifications
You must be signed in to change notification settings - Fork 25.1k
/
_gb.py
2613 lines (2125 loc) · 97.6 KB
/
_gb.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
"""Gradient Boosted Regression Trees
This module contains methods for fitting gradient boosted regression trees for
both classification and regression.
The module structure is the following:
- The ``BaseGradientBoosting`` base class implements a common ``fit`` method
for all the estimators in the module. Regression and classification
only differ in the concrete ``LossFunction`` used.
- ``GradientBoostingClassifier`` implements gradient boosting for
classification problems.
- ``GradientBoostingRegressor`` implements gradient boosting for
regression problems.
"""
# Authors: Peter Prettenhofer, Scott White, Gilles Louppe, Emanuele Olivetti,
# Arnaud Joly, Jacob Schreiber
# License: BSD 3 clause
from abc import ABCMeta
from abc import abstractmethod
import warnings
from ._base import BaseEnsemble
from ..base import ClassifierMixin
from ..base import RegressorMixin
from ..base import BaseEstimator
from ..base import is_classifier
from ._gradient_boosting import predict_stages
from ._gradient_boosting import predict_stage
from ._gradient_boosting import _random_sample_mask
import numbers
import numpy as np
from scipy.sparse import csc_matrix
from scipy.sparse import csr_matrix
from scipy.sparse import issparse
from scipy.special import expit
from time import time
from ..model_selection import train_test_split
from ..tree import DecisionTreeRegressor
from ..tree._tree import DTYPE, DOUBLE
from ..tree._tree import TREE_LEAF
from . import _gb_losses
from ..utils import check_random_state
from ..utils import check_array
from ..utils import column_or_1d
from ..utils import check_consistent_length
from ..utils import deprecated
from ..utils.fixes import logsumexp
from ..utils.stats import _weighted_percentile
from ..utils.validation import check_is_fitted
from ..utils.multiclass import check_classification_targets
from ..exceptions import NotFittedError
# FIXME: 0.23
# All the losses and corresponding init estimators have been moved to the
# _losses module in 0.21. We deprecate them and keep them here for now in case
# someone has imported them. None of these losses can be used as a parameter
# to a GBDT estimator anyway (loss param only accepts strings).
@deprecated("QuantileEstimator is deprecated in version "
"0.21 and will be removed in version 0.23.")
class QuantileEstimator:
"""An estimator predicting the alpha-quantile of the training targets.
Parameters
----------
alpha : float
The quantile
"""
def __init__(self, alpha=0.9):
if not 0 < alpha < 1.0:
raise ValueError("`alpha` must be in (0, 1.0) but was %r" % alpha)
self.alpha = alpha
def fit(self, X, y, sample_weight=None):
"""Fit the estimator.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data
y : array, shape (n_samples, n_targets)
Target values. Will be cast to X's dtype if necessary
sample_weight : numpy array of shape (n_samples,)
Individual weights for each sample
"""
if sample_weight is None:
self.quantile = np.percentile(y, self.alpha * 100.0)
else:
self.quantile = _weighted_percentile(y, sample_weight,
self.alpha * 100.0)
def predict(self, X):
"""Predict labels
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Samples.
Returns
-------
y : array, shape (n_samples,)
Returns predicted values.
"""
check_is_fitted(self)
y = np.empty((X.shape[0], 1), dtype=np.float64)
y.fill(self.quantile)
return y
@deprecated("MeanEstimator is deprecated in version "
"0.21 and will be removed in version 0.23.")
class MeanEstimator:
"""An estimator predicting the mean of the training targets."""
def fit(self, X, y, sample_weight=None):
"""Fit the estimator.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data
y : array, shape (n_samples, n_targets)
Target values. Will be cast to X's dtype if necessary
sample_weight : numpy array of shape (n_samples,)
Individual weights for each sample
"""
if sample_weight is None:
self.mean = np.mean(y)
else:
self.mean = np.average(y, weights=sample_weight)
def predict(self, X):
"""Predict labels
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Samples.
Returns
-------
y : array, shape (n_samples,)
Returns predicted values.
"""
check_is_fitted(self)
y = np.empty((X.shape[0], 1), dtype=np.float64)
y.fill(self.mean)
return y
@deprecated("LogOddsEstimator is deprecated in version "
"0.21 and will be removed in version 0.23.")
class LogOddsEstimator:
"""An estimator predicting the log odds ratio."""
scale = 1.0
def fit(self, X, y, sample_weight=None):
"""Fit the estimator.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data
y : array, shape (n_samples, n_targets)
Target values. Will be cast to X's dtype if necessary
sample_weight : numpy array of shape (n_samples,)
Individual weights for each sample
"""
# pre-cond: pos, neg are encoded as 1, 0
if sample_weight is None:
pos = np.sum(y)
neg = y.shape[0] - pos
else:
pos = np.sum(sample_weight * y)
neg = np.sum(sample_weight * (1 - y))
if neg == 0 or pos == 0:
raise ValueError('y contains non binary labels.')
self.prior = self.scale * np.log(pos / neg)
def predict(self, X):
"""Predict labels
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Samples.
Returns
-------
y : array, shape (n_samples,)
Returns predicted values.
"""
check_is_fitted(self)
y = np.empty((X.shape[0], 1), dtype=np.float64)
y.fill(self.prior)
return y
@deprecated("ScaledLogOddsEstimator is deprecated in version "
"0.21 and will be removed in version 0.23.")
class ScaledLogOddsEstimator(LogOddsEstimator):
"""Log odds ratio scaled by 0.5 -- for exponential loss. """
scale = 0.5
@deprecated("PriorProbablityEstimator is deprecated in version "
"0.21 and will be removed in version 0.23.")
class PriorProbabilityEstimator:
"""An estimator predicting the probability of each
class in the training data.
"""
def fit(self, X, y, sample_weight=None):
"""Fit the estimator.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data
y : array, shape (n_samples, n_targets)
Target values. Will be cast to X's dtype if necessary
sample_weight : array, shape (n_samples,)
Individual weights for each sample
"""
if sample_weight is None:
sample_weight = np.ones_like(y, dtype=np.float64)
class_counts = np.bincount(y, weights=sample_weight)
self.priors = class_counts / class_counts.sum()
def predict(self, X):
"""Predict labels
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Samples.
Returns
-------
y : array, shape (n_samples,)
Returns predicted values.
"""
check_is_fitted(self)
y = np.empty((X.shape[0], self.priors.shape[0]), dtype=np.float64)
y[:] = self.priors
return y
@deprecated("Using ZeroEstimator is deprecated in version "
"0.21 and will be removed in version 0.23.")
class ZeroEstimator:
"""An estimator that simply predicts zero.
.. deprecated:: 0.21
Using ``ZeroEstimator`` or ``init='zero'`` is deprecated in version
0.21 and will be removed in version 0.23.
"""
def fit(self, X, y, sample_weight=None):
"""Fit the estimator.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data
y : numpy, shape (n_samples, n_targets)
Target values. Will be cast to X's dtype if necessary
sample_weight : array, shape (n_samples,)
Individual weights for each sample
"""
if np.issubdtype(y.dtype, np.signedinteger):
# classification
self.n_classes = np.unique(y).shape[0]
if self.n_classes == 2:
self.n_classes = 1
else:
# regression
self.n_classes = 1
def predict(self, X):
"""Predict labels
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Samples.
Returns
-------
y : array, shape (n_samples,)
Returns predicted values.
"""
check_is_fitted(self)
y = np.empty((X.shape[0], self.n_classes), dtype=np.float64)
y.fill(0.0)
return y
def predict_proba(self, X):
return self.predict(X)
@deprecated("All Losses in sklearn.ensemble.gradient_boosting are "
"deprecated in version "
"0.21 and will be removed in version 0.23.")
class LossFunction(metaclass=ABCMeta):
"""Abstract base class for various loss functions.
Parameters
----------
n_classes : int
Number of classes
Attributes
----------
K : int
The number of regression trees to be induced;
1 for regression and binary classification;
``n_classes`` for multi-class classification.
"""
is_multi_class = False
def __init__(self, n_classes):
self.K = n_classes
def init_estimator(self):
"""Default ``init`` estimator for loss function. """
raise NotImplementedError()
@abstractmethod
def __call__(self, y, pred, sample_weight=None):
"""Compute the loss.
Parameters
----------
y : array, shape (n_samples,)
True labels
pred : array, shape (n_samples,)
Predicted labels
sample_weight : array-like, shape (n_samples,), optional
Sample weights.
"""
@abstractmethod
def negative_gradient(self, y, y_pred, **kargs):
"""Compute the negative gradient.
Parameters
----------
y : array, shape (n_samples,)
The target labels.
y_pred : array, shape (n_samples,)
The predictions.
"""
def update_terminal_regions(self, tree, X, y, residual, y_pred,
sample_weight, sample_mask,
learning_rate=0.1, k=0):
"""Update the terminal regions (=leaves) of the given tree and
updates the current predictions of the model. Traverses tree
and invokes template method `_update_terminal_region`.
Parameters
----------
tree : tree.Tree
The tree object.
X : array, shape (n, m)
The data array.
y : array, shape (n,)
The target labels.
residual : array, shape (n,)
The residuals (usually the negative gradient).
y_pred : array, shape (n,)
The predictions.
sample_weight : array, shape (n,)
The weight of each sample.
sample_mask : array, shape (n,)
The sample mask to be used.
learning_rate : float, default=0.1
learning rate shrinks the contribution of each tree by
``learning_rate``.
k : int, default 0
The index of the estimator being updated.
"""
# compute leaf for each sample in ``X``.
terminal_regions = tree.apply(X)
# mask all which are not in sample mask.
masked_terminal_regions = terminal_regions.copy()
masked_terminal_regions[~sample_mask] = -1
# update each leaf (= perform line search)
for leaf in np.where(tree.children_left == TREE_LEAF)[0]:
self._update_terminal_region(tree, masked_terminal_regions,
leaf, X, y, residual,
y_pred[:, k], sample_weight)
# update predictions (both in-bag and out-of-bag)
y_pred[:, k] += (learning_rate
* tree.value[:, 0, 0].take(terminal_regions, axis=0))
@abstractmethod
def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight):
"""Template method for updating terminal regions (=leaves). """
@deprecated("All Losses in sklearn.ensemble.gradient_boosting are "
"deprecated in version "
"0.21 and will be removed in version 0.23.")
class RegressionLossFunction(LossFunction, metaclass=ABCMeta):
"""Base class for regression loss functions.
Parameters
----------
n_classes : int
Number of classes
"""
def __init__(self, n_classes):
if n_classes != 1:
raise ValueError("``n_classes`` must be 1 for regression but "
"was %r" % n_classes)
super().__init__(n_classes)
@deprecated("All Losses in sklearn.ensemble.gradient_boosting are "
"deprecated in version "
"0.21 and will be removed in version 0.23.")
class LeastSquaresError(RegressionLossFunction):
"""Loss function for least squares (LS) estimation.
Terminal regions need not to be updated for least squares.
Parameters
----------
n_classes : int
Number of classes
"""
def init_estimator(self):
return MeanEstimator()
def __call__(self, y, pred, sample_weight=None):
"""Compute the least squares loss.
Parameters
----------
y : array, shape (n_samples,)
True labels
pred : array, shape (n_samples,)
Predicted labels
sample_weight : array-like, shape (n_samples,), optional
Sample weights.
"""
if sample_weight is None:
return np.mean((y - pred.ravel()) ** 2.0)
else:
return (1.0 / sample_weight.sum() *
np.sum(sample_weight * ((y - pred.ravel()) ** 2.0)))
def negative_gradient(self, y, pred, **kargs):
"""Compute the negative gradient.
Parameters
----------
y : array, shape (n_samples,)
The target labels.
pred : array, shape (n_samples,)
The predictions.
"""
return y - pred.ravel()
def update_terminal_regions(self, tree, X, y, residual, y_pred,
sample_weight, sample_mask,
learning_rate=0.1, k=0):
"""Least squares does not need to update terminal regions.
But it has to update the predictions.
Parameters
----------
tree : tree.Tree
The tree object.
X : array, shape (n, m)
The data array.
y : array, shape (n,)
The target labels.
residual : array, shape (n,)
The residuals (usually the negative gradient).
y_pred : array, shape (n,)
The predictions.
sample_weight : array, shape (n,)
The weight of each sample.
sample_mask : array, shape (n,)
The sample mask to be used.
learning_rate : float, default=0.1
learning rate shrinks the contribution of each tree by
``learning_rate``.
k : int, default 0
The index of the estimator being updated.
"""
# update predictions
y_pred[:, k] += learning_rate * tree.predict(X).ravel()
def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight):
pass
@deprecated("All Losses in sklearn.ensemble.gradient_boosting are "
"deprecated in version "
"0.21 and will be removed in version 0.23.")
class LeastAbsoluteError(RegressionLossFunction):
"""Loss function for least absolute deviation (LAD) regression.
Parameters
----------
n_classes : int
Number of classes
"""
def init_estimator(self):
return QuantileEstimator(alpha=0.5)
def __call__(self, y, pred, sample_weight=None):
"""Compute the least absolute error.
Parameters
----------
y : array, shape (n_samples,)
True labels
pred : array, shape (n_samples,)
Predicted labels
sample_weight : array-like, shape (n_samples,), optional
Sample weights.
"""
if sample_weight is None:
return np.abs(y - pred.ravel()).mean()
else:
return (1.0 / sample_weight.sum() *
np.sum(sample_weight * np.abs(y - pred.ravel())))
def negative_gradient(self, y, pred, **kargs):
"""Compute the negative gradient.
1.0 if y - pred > 0.0 else -1.0
Parameters
----------
y : array, shape (n_samples,)
The target labels.
pred : array, shape (n_samples,)
The predictions.
"""
pred = pred.ravel()
return 2.0 * (y - pred > 0.0) - 1.0
def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight):
"""LAD updates terminal regions to median estimates. """
terminal_region = np.where(terminal_regions == leaf)[0]
sample_weight = sample_weight.take(terminal_region, axis=0)
diff = y.take(terminal_region, axis=0) - pred.take(terminal_region, axis=0)
tree.value[leaf, 0, 0] = _weighted_percentile(diff, sample_weight, percentile=50)
@deprecated("All Losses in sklearn.ensemble.gradient_boosting are "
"deprecated in version "
"0.21 and will be removed in version 0.23.")
class HuberLossFunction(RegressionLossFunction):
"""Huber loss function for robust regression.
M-Regression proposed in Friedman 2001.
References
----------
J. Friedman, Greedy Function Approximation: A Gradient Boosting
Machine, The Annals of Statistics, Vol. 29, No. 5, 2001.
Parameters
----------
n_classes : int
Number of classes
alpha : float
Percentile at which to extract score
"""
def __init__(self, n_classes, alpha=0.9):
super().__init__(n_classes)
self.alpha = alpha
self.gamma = None
def init_estimator(self):
return QuantileEstimator(alpha=0.5)
def __call__(self, y, pred, sample_weight=None):
"""Compute the Huber loss.
Parameters
----------
y : array, shape (n_samples,)
True labels
pred : array, shape (n_samples,)
Predicted labels
sample_weight : array-like, shape (n_samples,), optional
Sample weights.
"""
pred = pred.ravel()
diff = y - pred
gamma = self.gamma
if gamma is None:
if sample_weight is None:
gamma = np.percentile(np.abs(diff), self.alpha * 100)
else:
gamma = _weighted_percentile(np.abs(diff), sample_weight, self.alpha * 100)
gamma_mask = np.abs(diff) <= gamma
if sample_weight is None:
sq_loss = np.sum(0.5 * diff[gamma_mask] ** 2.0)
lin_loss = np.sum(gamma * (np.abs(diff[~gamma_mask]) - gamma / 2.0))
loss = (sq_loss + lin_loss) / y.shape[0]
else:
sq_loss = np.sum(0.5 * sample_weight[gamma_mask] * diff[gamma_mask] ** 2.0)
lin_loss = np.sum(gamma * sample_weight[~gamma_mask] *
(np.abs(diff[~gamma_mask]) - gamma / 2.0))
loss = (sq_loss + lin_loss) / sample_weight.sum()
return loss
def negative_gradient(self, y, pred, sample_weight=None, **kargs):
"""Compute the negative gradient.
Parameters
----------
y : array, shape (n_samples,)
The target labels.
pred : array, shape (n_samples,)
The predictions.
sample_weight : array-like, shape (n_samples,), optional
Sample weights.
"""
pred = pred.ravel()
diff = y - pred
if sample_weight is None:
gamma = np.percentile(np.abs(diff), self.alpha * 100)
else:
gamma = _weighted_percentile(np.abs(diff), sample_weight, self.alpha * 100)
gamma_mask = np.abs(diff) <= gamma
residual = np.zeros((y.shape[0],), dtype=np.float64)
residual[gamma_mask] = diff[gamma_mask]
residual[~gamma_mask] = gamma * np.sign(diff[~gamma_mask])
self.gamma = gamma
return residual
def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight):
terminal_region = np.where(terminal_regions == leaf)[0]
sample_weight = sample_weight.take(terminal_region, axis=0)
gamma = self.gamma
diff = (y.take(terminal_region, axis=0)
- pred.take(terminal_region, axis=0))
median = _weighted_percentile(diff, sample_weight, percentile=50)
diff_minus_median = diff - median
tree.value[leaf, 0] = median + np.mean(
np.sign(diff_minus_median) *
np.minimum(np.abs(diff_minus_median), gamma))
@deprecated("All Losses in sklearn.ensemble.gradient_boosting are "
"deprecated in version "
"0.21 and will be removed in version 0.23.")
class QuantileLossFunction(RegressionLossFunction):
"""Loss function for quantile regression.
Quantile regression allows to estimate the percentiles
of the conditional distribution of the target.
Parameters
----------
n_classes : int
Number of classes.
alpha : float, optional (default = 0.9)
The percentile
"""
def __init__(self, n_classes, alpha=0.9):
super().__init__(n_classes)
self.alpha = alpha
self.percentile = alpha * 100.0
def init_estimator(self):
return QuantileEstimator(self.alpha)
def __call__(self, y, pred, sample_weight=None):
"""Compute the Quantile loss.
Parameters
----------
y : array, shape (n_samples,)
True labels
pred : array, shape (n_samples,)
Predicted labels
sample_weight : array-like, shape (n_samples,), optional
Sample weights.
"""
pred = pred.ravel()
diff = y - pred
alpha = self.alpha
mask = y > pred
if sample_weight is None:
loss = (alpha * diff[mask].sum() -
(1.0 - alpha) * diff[~mask].sum()) / y.shape[0]
else:
loss = ((alpha * np.sum(sample_weight[mask] * diff[mask]) -
(1.0 - alpha) * np.sum(sample_weight[~mask] * diff[~mask])) /
sample_weight.sum())
return loss
def negative_gradient(self, y, pred, **kargs):
"""Compute the negative gradient.
Parameters
----------
y : array, shape (n_samples,)
The target labels.
pred : array, shape (n_samples,)
The predictions.
"""
alpha = self.alpha
pred = pred.ravel()
mask = y > pred
return (alpha * mask) - ((1.0 - alpha) * ~mask)
def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight):
terminal_region = np.where(terminal_regions == leaf)[0]
diff = (y.take(terminal_region, axis=0)
- pred.take(terminal_region, axis=0))
sample_weight = sample_weight.take(terminal_region, axis=0)
val = _weighted_percentile(diff, sample_weight, self.percentile)
tree.value[leaf, 0] = val
@deprecated("All Losses in sklearn.ensemble.gradient_boosting are "
"deprecated in version "
"0.21 and will be removed in version 0.23.")
class ClassificationLossFunction(LossFunction, metaclass=ABCMeta):
"""Base class for classification loss functions. """
def _score_to_proba(self, score):
"""Template method to convert scores to probabilities.
the does not support probabilities raises AttributeError.
"""
raise TypeError('%s does not support predict_proba' % type(self).__name__)
@abstractmethod
def _score_to_decision(self, score):
"""Template method to convert scores to decisions.
Returns int arrays.
"""
@deprecated("All Losses in sklearn.ensemble.gradient_boosting are "
"deprecated in version "
"0.21 and will be removed in version 0.23.")
class BinomialDeviance(ClassificationLossFunction):
"""Binomial deviance loss function for binary classification.
Binary classification is a special case; here, we only need to
fit one tree instead of ``n_classes`` trees.
Parameters
----------
n_classes : int
Number of classes.
"""
def __init__(self, n_classes):
if n_classes != 2:
raise ValueError("{0:s} requires 2 classes; got {1:d} class(es)"
.format(self.__class__.__name__, n_classes))
# we only need to fit one tree for binary clf.
super().__init__(1)
def init_estimator(self):
return LogOddsEstimator()
def __call__(self, y, pred, sample_weight=None):
"""Compute the deviance (= 2 * negative log-likelihood).
Parameters
----------
y : array, shape (n_samples,)
True labels
pred : array, shape (n_samples,)
Predicted labels
sample_weight : array-like, shape (n_samples,), optional
Sample weights.
"""
# logaddexp(0, v) == log(1.0 + exp(v))
pred = pred.ravel()
if sample_weight is None:
return -2.0 * np.mean((y * pred) - np.logaddexp(0.0, pred))
else:
return (-2.0 / sample_weight.sum() *
np.sum(sample_weight * ((y * pred) - np.logaddexp(0.0, pred))))
def negative_gradient(self, y, pred, **kargs):
"""Compute the residual (= negative gradient).
Parameters
----------
y : array, shape (n_samples,)
True labels
pred : array, shape (n_samples,)
Predicted labels
"""
return y - expit(pred.ravel())
def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight):
"""Make a single Newton-Raphson step.
our node estimate is given by:
sum(w * (y - prob)) / sum(w * prob * (1 - prob))
we take advantage that: y - prob = residual
"""
terminal_region = np.where(terminal_regions == leaf)[0]
residual = residual.take(terminal_region, axis=0)
y = y.take(terminal_region, axis=0)
sample_weight = sample_weight.take(terminal_region, axis=0)
numerator = np.sum(sample_weight * residual)
denominator = np.sum(sample_weight * (y - residual) * (1 - y + residual))
# prevents overflow and division by zero
if abs(denominator) < 1e-150:
tree.value[leaf, 0, 0] = 0.0
else:
tree.value[leaf, 0, 0] = numerator / denominator
def _score_to_proba(self, score):
proba = np.ones((score.shape[0], 2), dtype=np.float64)
proba[:, 1] = expit(score.ravel())
proba[:, 0] -= proba[:, 1]
return proba
def _score_to_decision(self, score):
proba = self._score_to_proba(score)
return np.argmax(proba, axis=1)
@deprecated("All Losses in sklearn.ensemble.gradient_boosting are "
"deprecated in version "
"0.21 and will be removed in version 0.23.")
class MultinomialDeviance(ClassificationLossFunction):
"""Multinomial deviance loss function for multi-class classification.
For multi-class classification we need to fit ``n_classes`` trees at
each stage.
Parameters
----------
n_classes : int
Number of classes
"""
is_multi_class = True
def __init__(self, n_classes):
if n_classes < 3:
raise ValueError("{0:s} requires more than 2 classes.".format(
self.__class__.__name__))
super().__init__(n_classes)
def init_estimator(self):
return PriorProbabilityEstimator()
def __call__(self, y, pred, sample_weight=None):
"""Compute the Multinomial deviance.
Parameters
----------
y : array, shape (n_samples,)
True labels
pred : array, shape (n_samples,)
Predicted labels
sample_weight : array-like, shape (n_samples,), optional
Sample weights.
"""
# create one-hot label encoding
Y = np.zeros((y.shape[0], self.K), dtype=np.float64)
for k in range(self.K):
Y[:, k] = y == k
if sample_weight is None:
return np.sum(-1 * (Y * pred).sum(axis=1) +
logsumexp(pred, axis=1))
else:
return np.sum(-1 * sample_weight * (Y * pred).sum(axis=1) +
logsumexp(pred, axis=1))
def negative_gradient(self, y, pred, k=0, **kwargs):
"""Compute negative gradient for the ``k``-th class.
Parameters
----------
y : array, shape (n_samples,)
The target labels.
pred : array, shape (n_samples,)
The predictions.
k : int, optional (default=0)
The index of the class
"""
return y - np.nan_to_num(np.exp(pred[:, k] -
logsumexp(pred, axis=1)))
def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight):
"""Make a single Newton-Raphson step. """
terminal_region = np.where(terminal_regions == leaf)[0]
residual = residual.take(terminal_region, axis=0)
y = y.take(terminal_region, axis=0)
sample_weight = sample_weight.take(terminal_region, axis=0)
numerator = np.sum(sample_weight * residual)
numerator *= (self.K - 1) / self.K
denominator = np.sum(sample_weight * (y - residual) *
(1.0 - y + residual))
# prevents overflow and division by zero
if abs(denominator) < 1e-150:
tree.value[leaf, 0, 0] = 0.0
else:
tree.value[leaf, 0, 0] = numerator / denominator
def _score_to_proba(self, score):
return np.nan_to_num(
np.exp(score - (logsumexp(score, axis=1)[:, np.newaxis])))
def _score_to_decision(self, score):
proba = self._score_to_proba(score)
return np.argmax(proba, axis=1)