1
- import numpy as np
2
- import decision_tree
3
-
4
- class GBDT :
5
- def __sigmoid (self , x ):
6
- return 1 / (1 + np .exp (- x ))
7
-
8
- def __softmax (self , x ):
9
- return np .exp (x ) / np .sum (np .exp (x ), axis = 1 , keepdims = True )
10
-
11
- def __init__ (self , loss ):
12
- self .__models = []
13
- self .__alpha = []
14
- self .__loss = loss
15
-
16
- def fit (self , X , y , epochs , learning_rate ):
17
- self .__learning_rate = learning_rate
18
-
19
- residual = y
20
- for _ in range (epochs ):
21
- model = decision_tree .Cart ('regression' )
22
- model .fit (X , residual )
23
- self .__models .append (model )
24
-
25
- alpha = np .mean (residual / (model .predict (X ) + 1e-8 ), axis = 0 )
26
- self .__alpha .append (alpha )
27
-
28
- residual = y - self .score (X )
29
-
30
- def predict (self , X , classes = None ):
31
- if self .__loss == 'mse' :
32
- return self .score (X )
33
- elif self .__loss == 'binary_crossentropy' :
34
- return np .around (self .score (X ))
35
- elif self .__loss == 'categorical_crossentropy' :
36
- return classes [np .argmax (self .score (X ), axis = 1 )].reshape ((- 1 , 1 ))
37
-
38
- def score (self , X ):
39
- h = 0
40
- for alpha , model in zip (self .__alpha , self .__models ):
41
- h += self .__learning_rate * model .predict (X ) * alpha
42
-
43
- if self .__loss == 'mse' :
44
- return h
45
- elif self .__loss == 'binary_crossentropy' :
46
- return self .__sigmoid (h )
47
- elif self .__loss == 'categorical_crossentropy' :
48
- return self .__softmax (h )
1
+ import numpy as np
2
+ import decision_tree_cart
3
+ import scipy
4
+
5
+ class GBDT :
6
+ def __init__ (self , loss ):
7
+ self .__models = []
8
+ self .__alpha = []
9
+ self .__loss = loss
10
+
11
+ def fit (self , X , y , epochs , learning_rate ):
12
+ '''
13
+ Parameters
14
+ ----------
15
+ X : shape (n_samples, n_features)
16
+ Training data
17
+ y : shape (n_samples,)
18
+ Target values
19
+ epochs : The number of epochs
20
+ learning_rate : Learning rate
21
+ '''
22
+ self .__learning_rate = learning_rate
23
+
24
+ residual = y
25
+ for _ in range (epochs ):
26
+ model = decision_tree_cart .CART ('regression' )
27
+ model .fit (X , residual )
28
+ self .__models .append (model )
29
+
30
+ alpha = np .mean (residual / (model .predict (X ) + 1e-8 ), axis = 0 )
31
+ self .__alpha .append (alpha )
32
+
33
+ residual = y - self .score (X )
34
+
35
+ def predict (self , X ):
36
+ '''
37
+ Parameters
38
+ ----------
39
+ X : shape (n_samples, n_features)
40
+ Predicting data
41
+
42
+ Returns
43
+ -------
44
+ y : shape (n_samples,)
45
+ Predicted value per sample.
46
+ '''
47
+ if self .__loss == 'regression' :
48
+ return self .score (X )
49
+ elif self .__loss == 'classification' :
50
+ return np .around (self .score (X ))
51
+
52
+ def score (self , X ):
53
+ return self .__learning_rate * sum ([model .predict (X ) * alpha for alpha , model in zip (self .__alpha , self .__models )])
49
54
0 commit comments