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

slipper_util.py 8.9 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
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
  1. import random
  2. import numpy as np
  3. from sklearn.base import BaseEstimator, ClassifierMixin
  4. from sklearn.model_selection import train_test_split
  5. from imodels.util.arguments import check_fit_arguments
  6. class SlipperBaseEstimator(BaseEstimator, ClassifierMixin):
  7. """ An estimator that supports building rules as described in
  8. A Simple, Fast, and Effective Rule Learner (1999). Intended to be used
  9. as part of the SlipperRulesClassifier.
  10. """
  11. def __init__(self):
  12. self.Z = None
  13. self.rule = None
  14. self.D = None
  15. def _make_candidate(self, X, y, curr_rule, feat, A_c):
  16. """ Make candidate rules for grow routine to compare scores"""
  17. # make candidate rules
  18. candidates = [curr_rule.copy() for _ in range(3)]
  19. candidates = [
  20. x + [{
  21. 'feature': int(feat),
  22. 'operator': operator,
  23. 'pivot': float(A_c)}]
  24. for x, operator in zip(candidates, ['>', '<', '=='])
  25. ]
  26. # pick best condition
  27. Zs = [self._grow_rule_obj(X, y, r) for r in candidates]
  28. return candidates[Zs.index(max(Zs))]
  29. def _condition_classify(self, X, condition):
  30. """
  31. Helper function to make classifications for a condition
  32. in a rule
  33. """
  34. logic = 'X[:, {}] {} {}'.format(
  35. condition['feature'],
  36. condition['operator'],
  37. condition['pivot']
  38. )
  39. output = np.where(eval(logic))
  40. return output[0]
  41. def _rule_predict(self, X, rule):
  42. """ return all indices for which the passed rule holds on X """
  43. preds = np.zeros(X.shape[0])
  44. positive_cases = set(range(X.shape[0]))
  45. for condition in rule:
  46. outputs = set(list(self._condition_classify(X, condition)))
  47. positive_cases = positive_cases.intersection(outputs)
  48. preds[list(positive_cases)] = 1
  49. return preds
  50. def _get_design_matrices(self, X, y, rule):
  51. """ produce design matrices used in most equations"""
  52. preds = self._rule_predict(X, rule)
  53. W_plus_idx = np.where((preds == 1) & (y == 1))
  54. W_minus_idx = np.where((preds == 1) & (y == 0))
  55. return np.sum(self.D[W_plus_idx]), np.sum(self.D[W_minus_idx])
  56. def _grow_rule_obj(self, X, y, rule):
  57. """ equation to maximize in growing rule
  58. equation 6 from Cohen & Singer (1999)
  59. """
  60. W_plus, W_minus = self._get_design_matrices(X, y, rule)
  61. # C_R = self._sample_weight(W_plus, W_minus)
  62. return np.sqrt(W_plus) - np.sqrt(W_minus)
  63. def _sample_weight(self, plus, minus):
  64. """ Calculate learner sample weight
  65. in paper this is C_R, which is confidence of learner
  66. """
  67. return 0.5 * np.log((plus + (1 / (2 * len(self.D)))) /
  68. (minus + 1 / (2 * len(self.D))))
  69. def _grow_rule(self, X, y):
  70. """ Starts with empty conjunction of conditions and
  71. greedily adds rules to maximize Z_tilde
  72. """
  73. stop_condition = False
  74. features = list(range(X.shape[1]))
  75. # rule is stored as a list of dictionaries, each dictionary is a condition
  76. curr_rule = []
  77. while not stop_condition:
  78. candidate_rule = curr_rule.copy()
  79. for feat in features:
  80. try:
  81. pivots = np.percentile(X[:, feat], range(0, 100, 4),
  82. method='linear')
  83. except:
  84. pivots = np.percentile(X[:, feat], range(0, 100, 4), # deprecated
  85. interpolation='midpoint')
  86. # get a list of possible rules
  87. feature_candidates = [
  88. self._make_candidate(X, y, curr_rule, feat, A_c)
  89. for A_c in pivots
  90. ]
  91. # get max Z_tilde and update candidate accordingly
  92. tildes = [self._grow_rule_obj(X, y, r) for r in feature_candidates]
  93. if max(tildes) > self._grow_rule_obj(X, y, candidate_rule):
  94. candidate_rule = feature_candidates[
  95. tildes.index(max(tildes))
  96. ]
  97. preds = self._rule_predict(X, candidate_rule)
  98. negative_coverage = np.where((preds == y) & (y == 0))
  99. if self._grow_rule_obj(X, y, curr_rule) >= self._grow_rule_obj(X, y, candidate_rule) or \
  100. len(negative_coverage) == 0:
  101. stop_condition = True
  102. else:
  103. curr_rule = candidate_rule.copy()
  104. return curr_rule
  105. def _prune_rule(self, X, y, rule):
  106. """ Remove conditions from greedily built rule until
  107. objective does not improve
  108. """
  109. stop_condition = False
  110. curr_rule = rule.copy()
  111. while not stop_condition:
  112. candidate_rules = []
  113. if len(curr_rule) == 1:
  114. return curr_rule
  115. candidate_rules = [
  116. self._pop_condition(curr_rule, condition)
  117. for condition in curr_rule
  118. ]
  119. prune_objs = [self._prune_rule_obj(X, y, rule) for x in candidate_rules]
  120. best_prune = candidate_rules[
  121. prune_objs.index(min(prune_objs))
  122. ]
  123. if self._prune_rule_obj(X, y, rule) > self._prune_rule_obj(X, y, rule):
  124. curr_rule = best_prune.copy()
  125. else:
  126. stop_condition = True
  127. return curr_rule
  128. def _pop_condition(self, rule, condition):
  129. """
  130. Remove a condition from an existing Rule object
  131. """
  132. temp = rule.copy()
  133. temp.remove(condition)
  134. return temp
  135. def _make_default_rule(self, X, y):
  136. """
  137. Make the default rule that is true for every observation
  138. of data set. Without default rule a SlipperBaseEstimator would never
  139. predict negative
  140. """
  141. default_rule = []
  142. features = random.choices(
  143. range(X.shape[1]),
  144. k=random.randint(2, 8)
  145. )
  146. default_rule.append({
  147. 'feature': str(features[0]),
  148. 'operator': '>',
  149. 'pivot': str(min(X[:, features[0]]))
  150. })
  151. for i, x in enumerate(features):
  152. if i % 2:
  153. default_rule.append({
  154. 'feature': x,
  155. 'operator': '<',
  156. 'pivot': str(max(X[:, x]))
  157. })
  158. else:
  159. default_rule.append({
  160. 'feature': x,
  161. 'operator': '>',
  162. 'pivot': str(min(X[:, x]))
  163. })
  164. return default_rule
  165. def _prune_rule_obj(self, X, y, rule):
  166. """
  167. objective function for prune rule routine
  168. eq 7 from Cohen & Singer (1999)
  169. """
  170. V_plus, V_minus = self._get_design_matrices(X, y, rule)
  171. C_R = self._sample_weight(V_plus, V_minus)
  172. return (1 - V_plus - V_minus) + V_plus * np.exp(-C_R) \
  173. + V_minus * np.exp(C_R)
  174. def _eq_5(self, X, y, rule):
  175. """
  176. equation 5 from Cohen & Singer (1999)
  177. used to compare the learned rule with a default rule
  178. """
  179. W_plus, W_minus = self._get_design_matrices(X, y, rule)
  180. return 1 - np.square(np.sqrt(W_plus) - np.sqrt(W_minus))
  181. def _set_rule_or_default(self, X, y, learned_rule):
  182. """
  183. Compare output of eq 5 between learned rule and default rule
  184. return rule that minimizes eq 5
  185. """
  186. rules = [self._make_default_rule(X, y), learned_rule]
  187. scores = [self._eq_5(X, y, rule) for rule in rules]
  188. self.rule = rules[scores.index(min(scores))]
  189. def _make_feature_dict(self, num_features, features):
  190. """
  191. Map features to place holder names
  192. """
  193. if features is None:
  194. new_feats = ['X_' + str(i) for i in range(num_features)]
  195. else:
  196. new_feats = features
  197. self.feature_dict = {
  198. old_feat: new_feat for old_feat, new_feat in enumerate(new_feats)
  199. }
  200. def predict_proba(self, X):
  201. proba = self.predict(X)
  202. proba = proba.reshape(-1, 1)
  203. proba = np.hstack([
  204. np.zeros(proba.shape), proba
  205. ])
  206. return proba
  207. def predict(self, X):
  208. """
  209. external predict function that returns predictions
  210. using estimators rule
  211. """
  212. return self._rule_predict(X, self.rule)
  213. def fit(self, X, y, sample_weight=None, feature_names=None):
  214. """
  215. Main loop for training
  216. """
  217. X, y, feature_names = check_fit_arguments(self, X, y, feature_names)
  218. if sample_weight is not None:
  219. self.D = sample_weight
  220. X_grow, X_prune, y_grow, y_prune = \
  221. train_test_split(X, y, test_size=0.33)
  222. self._make_feature_dict(X.shape[1], feature_names)
  223. rule = self._grow_rule(X_grow, y_grow)
  224. rule = self._prune_rule(X_prune, y_prune, rule)
  225. self._set_rule_or_default(X, y, rule)
  226. return self
Tip!

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

Comments

Loading...