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

extract.py 8.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
  1. from typing import Iterable, Tuple, List
  2. import numpy as np
  3. import pandas as pd
  4. from mlxtend import frequent_patterns as mlx
  5. from sklearn.ensemble import BaggingRegressor, GradientBoostingRegressor, RandomForestRegressor, \
  6. GradientBoostingClassifier, RandomForestClassifier
  7. from sklearn.tree import DecisionTreeRegressor
  8. from sklearn.utils.validation import check_array
  9. import inspect
  10. from imodels.util import rule, convert
  11. def extract_fpgrowth(X,
  12. minsupport=0.1,
  13. maxcardinality=2,
  14. verbose=False) -> List[Tuple]:
  15. itemsets_df = mlx.fpgrowth(
  16. X, min_support=minsupport, max_len=maxcardinality)
  17. itemsets_indices = [tuple(s[1]) for s in itemsets_df.values]
  18. itemsets = [np.array(X.columns)[list(inds)] for inds in itemsets_indices]
  19. itemsets = list(map(tuple, itemsets))
  20. if verbose:
  21. print(len(itemsets), 'rules mined')
  22. return itemsets
  23. def extract_rulefit(X, y, feature_names,
  24. n_estimators=10,
  25. tree_size=4,
  26. memory_par=0.01,
  27. tree_generator=None,
  28. exp_rand_tree_size=True,
  29. random_state=None) -> List[str]:
  30. if tree_generator is None:
  31. sample_fract_ = min(0.5, (100 + 6 * np.sqrt(X.shape[0])) / X.shape[0])
  32. tree_generator = GradientBoostingRegressor(n_estimators=n_estimators,
  33. max_leaf_nodes=tree_size,
  34. learning_rate=memory_par,
  35. subsample=sample_fract_,
  36. random_state=random_state,
  37. max_depth=100)
  38. if type(tree_generator) not in [GradientBoostingClassifier, GradientBoostingRegressor,
  39. RandomForestRegressor, RandomForestClassifier]:
  40. raise ValueError(
  41. "RuleFit only works with GradientBoostingClassifier(), GradientBoostingRegressor(), "
  42. "RandomForestRegressor() or RandomForestClassifier()")
  43. # fit tree generator
  44. if not exp_rand_tree_size: # simply fit with constant tree size
  45. tree_generator.fit(X, y)
  46. else: # randomise tree size as per Friedman 2005 Sec 3.3
  47. np.random.seed(random_state)
  48. tree_sizes = np.random.exponential(
  49. scale=tree_size - 2, size=n_estimators)
  50. tree_sizes = np.asarray([2 + np.floor(tree_sizes[i_])
  51. for i_ in np.arange(len(tree_sizes))], dtype=int)
  52. tree_generator.set_params(warm_start=True)
  53. curr_est_ = 0
  54. for i_size in np.arange(len(tree_sizes)):
  55. size = tree_sizes[i_size]
  56. tree_generator.set_params(n_estimators=curr_est_ + 1)
  57. tree_generator.set_params(max_leaf_nodes=size)
  58. random_state_add = random_state if random_state else 0
  59. tree_generator.set_params(
  60. random_state=i_size + random_state_add) # warm_state=True seems to reset random_state, such that the trees are highly correlated, unless we manually change the random_sate here.
  61. tree_generator.fit(np.copy(X, order='C'), np.copy(y, order='C'))
  62. curr_est_ = curr_est_ + 1
  63. tree_generator.set_params(warm_start=False)
  64. if isinstance(tree_generator, RandomForestRegressor) or isinstance(tree_generator, RandomForestClassifier):
  65. estimators_ = [[x] for x in tree_generator.estimators_]
  66. else:
  67. estimators_ = tree_generator.estimators_
  68. seen_rules = set()
  69. extracted_rules = []
  70. for estimator in estimators_:
  71. for rule_value_pair in convert.tree_to_rules(estimator[0], np.array(feature_names), prediction_values=True):
  72. rule_obj = rule.Rule(rule_value_pair[0])
  73. if rule_obj not in seen_rules:
  74. extracted_rules.append(rule_value_pair)
  75. seen_rules.add(rule_obj)
  76. extracted_rules = sorted(extracted_rules, key=lambda x: x[1])
  77. extracted_rules = list(map(lambda x: x[0], extracted_rules))
  78. return extracted_rules
  79. def extract_skope(X, y, feature_names,
  80. sample_weight=None,
  81. n_estimators=10,
  82. max_samples=.8,
  83. max_samples_features=1.,
  84. bootstrap=False,
  85. bootstrap_features=False,
  86. max_depths=[3],
  87. max_features=1.,
  88. min_samples_split=2,
  89. n_jobs=1,
  90. random_state=None,
  91. verbose=0) -> Tuple[List[str], List[np.array], List[np.array]]:
  92. ensembles = []
  93. if not isinstance(max_depths, Iterable):
  94. max_depths = [max_depths]
  95. for max_depth in max_depths:
  96. # pass different key based on sklearn version
  97. estimator = DecisionTreeRegressor(
  98. max_depth=max_depth,
  99. max_features=max_features,
  100. min_samples_split=min_samples_split,
  101. )
  102. init_signature = inspect.signature(BaggingRegressor.__init__)
  103. estimator_key = 'estimator' if 'estimator' in init_signature.parameters.keys(
  104. ) else 'base_estimator'
  105. kwargs = {
  106. estimator_key: estimator,
  107. }
  108. bagging_clf = BaggingRegressor(
  109. n_estimators=n_estimators,
  110. max_samples=max_samples,
  111. max_features=max_samples_features,
  112. bootstrap=bootstrap,
  113. bootstrap_features=bootstrap_features,
  114. # oob_score=... XXX may be added
  115. # if selection on tree perf needed.
  116. # warm_start=... XXX may be added to increase computation perf.
  117. n_jobs=n_jobs,
  118. random_state=random_state,
  119. verbose=verbose,
  120. **kwargs
  121. )
  122. ensembles.append(bagging_clf)
  123. y_reg = y
  124. if sample_weight is not None:
  125. sample_weight = check_array(sample_weight, ensure_2d=False)
  126. weights = sample_weight - sample_weight.min()
  127. contamination = float(sum(y)) / len(y)
  128. y_reg = (
  129. pow(weights, 0.5) * 0.5 / contamination * (y > 0) -
  130. pow((weights).mean(), 0.5) * (y == 0)
  131. )
  132. y_reg = 1. / (1 + np.exp(-y_reg)) # sigmoid
  133. for e in ensembles[:len(ensembles) // 2]:
  134. e.fit(X, y)
  135. for e in ensembles[len(ensembles) // 2:]:
  136. e.fit(X, y_reg)
  137. estimators_, estimators_samples_, estimators_features_ = [], [], []
  138. for ensemble in ensembles:
  139. estimators_ += ensemble.estimators_
  140. estimators_samples_ += ensemble.estimators_samples_
  141. estimators_features_ += ensemble.estimators_features_
  142. extracted_rules = []
  143. for estimator, features in zip(estimators_, estimators_features_):
  144. extracted_rules.append(convert.tree_to_rules(
  145. estimator, np.array(feature_names)[features]))
  146. return extracted_rules, estimators_samples_, estimators_features_
  147. def extract_marginal_curves(clf, X, max_evals=100):
  148. """Uses predict_proba to compute marginal curves.
  149. Assumes clf is a classifier with a predict_proba method and that classifier is additive across features
  150. For GAM, this returns the shape functions
  151. Params
  152. ------
  153. clf : classifier
  154. A classifier with a predict_proba method
  155. X : array-like
  156. The data to compute the marginal curves on (used to calculate unique feature vals)
  157. max_evals : int
  158. The maximum number of evaluations to make for each feature
  159. Returns
  160. -------
  161. feature_vals_list : list of arrays
  162. The values of each feature for which the shape function is evaluated.
  163. shape_function_vals_list : list of arrays
  164. The shape function evaluated at each value of the corresponding feature.
  165. """
  166. p = X.shape[1]
  167. dummy_input = np.zeros((1, p))
  168. base = clf.predict_proba(dummy_input)[:, 1][0]
  169. feature_vals_list = []
  170. shape_function_vals_list = []
  171. for feat_num in range(p):
  172. feature_vals = sorted(np.unique(X[:, feat_num]))
  173. while len(feature_vals) > max_evals:
  174. feature_vals = feature_vals[::2]
  175. dummy_input = np.zeros((len(feature_vals), p))
  176. dummy_input[:, feat_num] = feature_vals
  177. shape_function_vals = clf.predict_proba(dummy_input)[:, 1] - base
  178. feature_vals_list.append(feature_vals)
  179. shape_function_vals_list.append(shape_function_vals.tolist())
  180. return feature_vals_list, shape_function_vals_list
  181. if __name__ == '__main__':
  182. init_signature = inspect.signature(BaggingRegressor.__init__)
  183. print('estimator' in init_signature.parameters.keys())
Tip!

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

Comments

Loading...