Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

custom_greedy_tree.py 7.5 KB

You have to be logged in to leave a comment. Sign In
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
  1. from sklearn.tree._tree import Tree
  2. from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
  3. from sklearn.base import ClassifierMixin, RegressorMixin
  4. from sklearn import __version__
  5. from collections import namedtuple
  6. import pandas as pd
  7. import numpy as np
  8. from collections import namedtuple
  9. from sklearn import __version__
  10. from sklearn.base import ClassifierMixin, RegressorMixin
  11. from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
  12. from sklearn.tree._tree import Tree
  13. import imodels.util.tree
  14. class Node:
  15. def __init__(self, impurity, num_samples, num_samples_per_class, predicted_probs):
  16. self.impurity = impurity
  17. self.num_samples = num_samples
  18. self.num_samples_per_class = num_samples_per_class
  19. self.predicted_probs = predicted_probs
  20. self.feature_index = 0
  21. self.threshold = 0
  22. self.left = None
  23. self.right = None
  24. class CustomDecisionTreeClassifier(ClassifierMixin):
  25. def __init__(self, max_leaf_nodes=None, impurity_func='gini'):
  26. self.root = None
  27. self.max_leaf_nodes = max_leaf_nodes
  28. self.impurity_func = impurity_func
  29. def fit(self, X, y, feature_costs=None):
  30. self.n_classes_ = len(set(y))
  31. self.n_features = X.shape[1]
  32. self.feature_costs_ = imodels.util.tree._validate_feature_costs(
  33. feature_costs, self.n_features)
  34. self.root = self._grow_tree(X, y)
  35. def _grow_tree(self, X, y):
  36. stack = []
  37. num_samples_per_class = np.array([np.sum(y == i)
  38. for i in range(self.n_classes_)])
  39. root = Node(
  40. impurity=self._calc_impurity(y),
  41. num_samples=y.size,
  42. num_samples_per_class=num_samples_per_class,
  43. predicted_probs=num_samples_per_class / y.size,
  44. )
  45. root.impurity_reduction = self._best_split(X, y)[-1]
  46. stack.append((root, X, y))
  47. self.n_splits = 0
  48. while stack:
  49. node, X_node, y_node = stack.pop()
  50. idx, thr, _ = self._best_split(X_node, y_node)
  51. if idx is not None:
  52. self.n_splits += 1
  53. indices_left = X_node[:, idx] < thr
  54. X_left, y_left = X_node[indices_left], y_node[indices_left]
  55. X_right, y_right = X_node[~indices_left], y_node[~indices_left]
  56. node.feature_index = idx
  57. node.threshold = thr
  58. num_samples_per_class_left = np.array([
  59. np.sum(y_left == i) for i in range(self.n_classes_)])
  60. node.left = Node(
  61. impurity=self._calc_impurity(y_left),
  62. num_samples=y_left.size,
  63. num_samples_per_class=num_samples_per_class_left,
  64. predicted_probs=num_samples_per_class_left / y_left.size,
  65. )
  66. # some redundant calculation going on here, but it's okay....
  67. node.left.impurity_reduction = self._best_split(
  68. X_left, y_left)[-1]
  69. num_samples_per_class_right = np.array([
  70. np.sum(y_right == i) for i in range(self.n_classes_)])
  71. node.right = Node(
  72. impurity=self._calc_impurity(y_right),
  73. num_samples=y_right.size,
  74. num_samples_per_class=num_samples_per_class_right,
  75. predicted_probs=num_samples_per_class_right / y_right.size,
  76. )
  77. node.right.impurity_reduction = self._best_split(
  78. X_right, y_right)[-1]
  79. stack.append((node.right, X_right, y_right))
  80. stack.append((node.left, X_left, y_left))
  81. # early stop
  82. if self.max_leaf_nodes and self.n_splits >= self.max_leaf_nodes - 1:
  83. return root
  84. # sort stack by impurity_reduction
  85. stack = sorted(
  86. stack, key=lambda x: x[0].impurity_reduction, reverse=True)
  87. return root
  88. def _best_split(self, X, y):
  89. n = y.size
  90. if n <= 1:
  91. return None, None, 0
  92. orig_impurity = self._gini(y)
  93. impurity_reduction = 0
  94. best_impurity_reduction = 0
  95. best_idx, best_thr = None, None
  96. # loop over features
  97. for idx in range(self.n_features):
  98. thresholds, y_classes = zip(*sorted(zip(X[:, idx], y)))
  99. y_classes = np.array(y_classes)
  100. # consider every point where threshold value changes
  101. idx_thresholds = (1 + np.where(np.diff(thresholds))[0]).tolist()
  102. for i in idx_thresholds:
  103. # calculate impurity for left and right
  104. y_left = y_classes[:i]
  105. y_right = y_classes[i:]
  106. impurity_reduction = orig_impurity - (y_left.size * self._gini(y_left) +
  107. y_right.size * self._gini(y_right)) / n
  108. if self.impurity_func == 'information_gain_ratio':
  109. split_info = - (y_left.size / n * np.log2(y_left.size / n)) - (
  110. y_right.size / n * np.log2(y_right.size / n))
  111. if ~np.isnan(split_info):
  112. impurity_reduction = impurity_reduction / split_info
  113. if self.impurity_func == 'cost_information_gain_ratio':
  114. impurity_reduction /= self.feature_costs_[idx]
  115. if impurity_reduction > best_impurity_reduction:
  116. best_impurity_reduction = impurity_reduction
  117. best_idx = idx
  118. best_thr = (thresholds[i] + thresholds[i - 1]) / 2
  119. return best_idx, best_thr, impurity_reduction
  120. def _calc_impurity(self, y):
  121. if self.impurity_func == 'gini':
  122. return self._gini(y)
  123. elif self.impurity_func in ['entropy', 'information_gain_ratio', 'cost_information_gain_ratio']:
  124. return self._entropy(y)
  125. def _gini(self, y):
  126. n = y.size
  127. return 1.0 - sum((np.sum(y == c) / n) ** 2 for c in range(self.n_classes_))
  128. def _entropy(self, y):
  129. n = y.size
  130. return -sum((np.sum(y == c) / n) * np.log2(np.sum(y == c) / n) for c in range(self.n_classes_))
  131. def predict(self, X):
  132. return np.argmax(self.predict_proba(X), axis=1)
  133. def predict_proba(self, X):
  134. return np.array([self._predict_single_proba(x) for x in X])
  135. def _predict_single_proba(self, x):
  136. node = self.root
  137. while node.left or node.right:
  138. if x[node.feature_index] < node.threshold and node.left:
  139. node = node.left
  140. elif node.right:
  141. node = node.right
  142. return node.predicted_probs
  143. if __name__ == '__main__':
  144. from sklearn.datasets import load_breast_cancer, load_iris
  145. from sklearn.model_selection import train_test_split
  146. from sklearn.metrics import accuracy_score
  147. # data = load_breast_cancer()
  148. data = load_iris()
  149. X = data.data
  150. y = data.target
  151. # print(np.unique(y))
  152. X_train, X_test, y_train, y_test = train_test_split(
  153. X, y, random_state=42, test_size=0.5)
  154. m = CustomDecisionTreeClassifier(
  155. # max_leaf_nodes=20,
  156. impurity_func='cost_information_gain_ratio')
  157. m.fit(X_train, y_train)
  158. y_pred = m.predict(X_test)
  159. print("Accuracy:", accuracy_score(y_test, y_pred))
  160. print('n_nodes', m.n_splits + 1)
  161. print('shapes', m.predict_proba(X_test).shape, m.predict(X_test).shape)
  162. cost = imodels.util.tree.calculate_mean_depth_of_points_in_custom_tree(m)
  163. print('Cost', cost)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...