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

tree.py 6.8 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
  1. from sklearn import datasets
  2. from sklearn.tree import DecisionTreeRegressor
  3. import numpy as np
  4. from sklearn.tree._tree import Tree
  5. from imodels.tree.custom_greedy_tree import CustomDecisionTreeClassifier
  6. def compute_tree_complexity(tree, complexity_measure='num_rules'):
  7. """Calculate number of non-leaf nodes
  8. """
  9. children_left = tree.children_left
  10. children_right = tree.children_right
  11. # num_split_nodes = 0
  12. complexity = 0
  13. stack = [(0, 0)] # start with the root node id (0) and its depth (0)
  14. while len(stack) > 0:
  15. # `pop` ensures each node is only visited once
  16. node_id, depth = stack.pop()
  17. # If the left and right child of a node is not the same we have a split
  18. # node
  19. is_split_node = children_left[node_id] != children_right[node_id]
  20. # If a split node, append left and right children and depth to `stack`
  21. # so we can loop through them
  22. if is_split_node:
  23. if complexity_measure == 'num_rules':
  24. complexity += 1
  25. stack.append((children_left[node_id], depth + 1))
  26. stack.append((children_right[node_id], depth + 1))
  27. else:
  28. if complexity_measure != 'num_rules':
  29. complexity += 1
  30. return complexity
  31. def _validate_feature_costs(feature_costs, n_features):
  32. if feature_costs is None:
  33. feature_costs = np.ones(n_features, dtype=np.float64)
  34. else:
  35. assert len(
  36. feature_costs) == n_features, f'{len(feature_costs)} != {n_features}'
  37. np.min(feature_costs) >= 0
  38. return feature_costs
  39. def calculate_mean_depth_of_points_in_tree(tree, X, feature_costs=None):
  40. """Calculate the mean depth of each point in the tree.
  41. This is the average depth of the path from the root to the point.
  42. """
  43. feature_costs = _validate_feature_costs(
  44. feature_costs, n_features=X.shape[1])
  45. if isinstance(tree, CustomDecisionTreeClassifier):
  46. return _mean_depth_custom_tree(tree, X, feature_costs)
  47. elif hasattr(tree, 'tree_'):
  48. return _mean_depth_sklearn_tree(tree.tree_, X, feature_costs)
  49. elif hasattr(tree, 'estimator_'):
  50. return _mean_depth_sklearn_tree(tree.estimator_.tree_, X, feature_costs)
  51. else:
  52. return _mean_depth_coct_tree(tree, X, feature_costs)
  53. def _mean_depth_custom_tree(custom_tree_, X, feature_costs):
  54. node = custom_tree_.root
  55. n_samples = []
  56. cum_costs = []
  57. is_leaves = []
  58. stack = [(node, 0)]
  59. while len(stack) > 0:
  60. node, cost = stack.pop()
  61. n_samples.append(node.num_samples)
  62. cum_costs.append(cost)
  63. is_leaves.append(node.left is None and node.right is None)
  64. if node.left:
  65. stack.append((node.left, cost + feature_costs[node.feature_index]))
  66. if node.right:
  67. stack.append(
  68. (node.right, cost + feature_costs[node.feature_index]))
  69. is_leaves = np.array(is_leaves)
  70. cum_costs = np.array(cum_costs)[is_leaves]
  71. n_samples = np.array(n_samples)[is_leaves]
  72. costs = cum_costs * n_samples / np.sum(n_samples)
  73. return np.sum(costs)
  74. def _mean_depth_sklearn_tree(tree_, X, feature_costs):
  75. n_nodes = tree_.node_count
  76. children_left = tree_.children_left
  77. children_right = tree_.children_right
  78. # things to compute
  79. _node_depth = np.zeros(shape=n_nodes, dtype=np.int64)
  80. _is_leaves = np.zeros(shape=n_nodes, dtype=bool)
  81. _cum_costs = np.zeros(shape=n_nodes, dtype=np.float64)
  82. # start with the root node id (0) and its depth (0) and its cost (0)
  83. stack = [(0, 0, 0)]
  84. while len(stack) > 0:
  85. node_id, depth, cost = stack.pop()
  86. _node_depth[node_id] = depth
  87. _cum_costs[node_id] = cost
  88. is_split_node = children_left[node_id] != children_right[node_id]
  89. cost += feature_costs[tree_.feature[node_id]]
  90. if is_split_node:
  91. stack.append((children_left[node_id], depth + 1, cost))
  92. stack.append((children_right[node_id], depth + 1, cost))
  93. else:
  94. _is_leaves[node_id] = True
  95. # iterate over leaves and calculate the number of samples in each of them
  96. n_samples = tree_.n_node_samples
  97. leaf_samples = n_samples[_is_leaves].astype(np.float64)
  98. depths = _cum_costs[_is_leaves] * leaf_samples / np.sum(leaf_samples)
  99. return np.sum(depths)
  100. def _mean_depth_coct_tree(coct_tree, X, feature_costs):
  101. indicator = coct_tree.decision_path(X)[:, coct_tree.branch_nodes]
  102. feature_use_counts = indicator.sum(axis=0)
  103. n_branch_nodes = indicator.shape[1]
  104. node_idx_to_feature_cost = {
  105. i: feature_costs[coct_tree.feature_[i]] for i in range(n_branch_nodes)
  106. }
  107. cost = sum(
  108. [node_idx_to_feature_cost[i] * feature_use_counts[i]
  109. for i in range(n_branch_nodes)]
  110. ) / len(X)
  111. return cost
  112. def calculate_mean_unique_calls_in_ensemble(ensemble, X, feature_costs=None):
  113. '''Calculate the mean number of unique calls in the ensemble.
  114. '''
  115. if X is None:
  116. # Should pass X, this is just for testing
  117. n_features_in = ensemble.n_features_in_
  118. X = np.random.randint(2, size=(100, n_features_in))
  119. if feature_costs is None:
  120. feature_costs = np.ones(n_features_in, dtype=np.float64)
  121. else:
  122. assert len(
  123. feature_costs) == n_features_in, f'{len(feature_costs)} != {n_features_in}'
  124. np.min(feature_costs) >= 0
  125. # extract the decision path for each sample
  126. ests = ensemble.estimators_.flatten()
  127. feats = [set() for _ in range(len(X))]
  128. for i in range(len(ests)):
  129. est = ests[i]
  130. node_index = est.decision_path(X).toarray()
  131. feats_est = [
  132. set([est.tree_.feature[x] for x in np.nonzero(row)[0]])
  133. for row in node_index
  134. ]
  135. for j in range(len(feats)):
  136. feats[j] = feats[j].union(feats_est[j])
  137. # -1 for the -2 feature that is always present
  138. return np.mean([len(f) - 1 for f in feats])
  139. def compute_mean_llm_calls(model_name, num_prompts, model=None, X=None):
  140. if model_name == "manual_tree":
  141. return calculate_mean_depth_of_points_in_tree(model.tree_)
  142. elif model_name == "manual_hstree":
  143. return calculate_mean_depth_of_points_in_tree(model.estimator_.tree_)
  144. elif model_name == "manual_gbdt":
  145. return calculate_mean_unique_calls_in_ensemble(model, X)
  146. elif model_name == "manual_tree_cv":
  147. return calculate_mean_depth_of_points_in_tree(model.best_estimator_.tree_)
  148. elif model_name in ["manual_single_prompt"]:
  149. return 1
  150. elif model_name in ["manual_ensemble", "manual_boosting"]:
  151. return num_prompts
  152. else:
  153. return num_prompts
  154. if __name__ == '__main__':
  155. X, y = datasets.fetch_california_housing(return_X_y=True) # regression
  156. m = DecisionTreeRegressor(random_state=42, max_leaf_nodes=4)
  157. m.fit(X, y)
  158. print(compute_tree_complexity(m.tree_, complexity_measure='num_leaves'))
Tip!

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

Comments

Loading...