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

figs_ensembles.py 24 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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
  1. from copy import deepcopy
  2. import numpy as np
  3. from matplotlib import pyplot as plt
  4. from sklearn import datasets
  5. from sklearn import tree
  6. from sklearn.base import BaseEstimator
  7. from sklearn.linear_model import RidgeCV, RidgeClassifierCV
  8. from sklearn.model_selection import train_test_split
  9. from sklearn.tree import plot_tree
  10. from sklearn.utils import check_X_y
  11. from imodels.tree.viz_utils import extract_sklearn_tree_from_figs
  12. class Node:
  13. def __init__(self, feature: int = None, threshold: int = None,
  14. value=None, idxs=None, is_root: bool = False, left=None,
  15. impurity_reduction: float = None, tree_num: int = None,
  16. right=None, split_or_linear='split', n_samples=0):
  17. """Node class for splitting
  18. """
  19. # split or linear
  20. self.is_root = is_root
  21. self.idxs = idxs
  22. self.tree_num = tree_num
  23. self.split_or_linear = split_or_linear
  24. self.feature = feature
  25. self.n_samples = n_samples
  26. self.impurity_reduction = impurity_reduction
  27. # different meanings
  28. self.value = value # for split this is mean, for linear this is weight
  29. # split-specific (for linear these should all be None)
  30. self.threshold = threshold
  31. self.left = left
  32. self.right = right
  33. self.left_temp = None
  34. self.right_temp = None
  35. def update_values(self, X, y):
  36. self.value = y.mean()
  37. if self.threshold is not None:
  38. right_indicator = np.apply_along_axis(
  39. lambda x: x[self.feature] > self.threshold, 1, X)
  40. X_right = X[right_indicator, :]
  41. X_left = X[~right_indicator, :]
  42. y_right = y[right_indicator]
  43. y_left = y[~right_indicator]
  44. if self.left is not None:
  45. self.left.update_values(X_left, y_left)
  46. if self.right is not None:
  47. self.right.update_values(X_right, y_right)
  48. def shrink(self, reg_param, cum_sum=0):
  49. if self.is_root:
  50. cum_sum = self.value
  51. if self.left is None: # if leaf node, change prediction
  52. self.value = cum_sum
  53. else:
  54. shrunk_diff = (self.left.value - self.value) / \
  55. (1 + reg_param / self.n_samples)
  56. self.left.shrink(reg_param, cum_sum + shrunk_diff)
  57. shrunk_diff = (self.right.value - self.value) / \
  58. (1 + reg_param / self.n_samples)
  59. self.right.shrink(reg_param, cum_sum + shrunk_diff)
  60. def setattrs(self, **kwargs):
  61. for k, v in kwargs.items():
  62. setattr(self, k, v)
  63. def __str__(self):
  64. if self.split_or_linear == 'linear':
  65. if self.is_root:
  66. return f'X_{self.feature} * {self.value:0.3f} (Tree #{self.tree_num} linear root)'
  67. else:
  68. return f'X_{self.feature} * {self.value:0.3f} (linear)'
  69. else:
  70. if self.is_root:
  71. return f'X_{self.feature} <= {self.threshold:0.3f} (Tree #{self.tree_num} root)'
  72. elif self.left is None and self.right is None:
  73. return f'Val: {self.value[0][0]:0.3f} (leaf)'
  74. else:
  75. return f'X_{self.feature} <= {self.threshold:0.3f} (split)'
  76. def __repr__(self):
  77. return self.__str__()
  78. class FIGSExt(BaseEstimator):
  79. """FIGSExt (sum of trees) classifier.
  80. Fast Interpretable Greedy-Tree Sums (FIGS) is an algorithm for fitting concise rule-based models.
  81. Specifically, FIGS generalizes CART to simultaneously grow a flexible number of trees in a summation.
  82. The total number of splits across all the trees can be restricted by a pre-specified threshold, keeping the model interpretable.
  83. Experiments across a wide array of real-world datasets show that FIGS achieves state-of-the-art prediction performance when restricted to just a few splits (e.g. less than 20).
  84. https://arxiv.org/abs/2201.11931
  85. """
  86. def __init__(self, max_rules: int = None, posthoc_ridge: bool = False,
  87. include_linear: bool = False,
  88. max_features=None, min_impurity_decrease: float = 0.0,
  89. k1: int = 0, k2: int = 0):
  90. """
  91. max_features
  92. The number of features to consider when looking for the best split
  93. k1: number of iterations of tree-prediction backfitting to do after making each split
  94. k2: number of iterations of tree-prediction backfitting to do after the end of the entire
  95. tree-growing phase
  96. """
  97. super().__init__()
  98. self.max_rules = max_rules
  99. self.posthoc_ridge = posthoc_ridge
  100. self.include_linear = include_linear
  101. self.max_features = max_features
  102. self.weighted_model_ = None # set if using posthoc_ridge
  103. self.min_impurity_decrease = min_impurity_decrease
  104. self.k1 = k1
  105. self.k2 = k2
  106. self._init_prediction_task() # decides between regressor and classifier
  107. def _init_prediction_task(self):
  108. """
  109. FIGSExtRegressor and FIGSExtClassifier override this method
  110. to alter the prediction task. When using this class directly,
  111. it is equivalent to FIGSExtRegressor
  112. """
  113. self.prediction_task = 'regression'
  114. def _init_decision_function(self):
  115. """Sets decision function based on prediction_task
  116. """
  117. # used by sklearn GridSearchCV, BaggingClassifier
  118. if self.prediction_task == 'classification':
  119. def decision_function(x): return self.predict_proba(x)[:, 1]
  120. elif self.prediction_task == 'regression':
  121. decision_function = self.predict
  122. def _construct_node_linear(self, X, y, idxs, tree_num=0, sample_weight=None):
  123. """This can be made a lot faster
  124. Assumes there are at least 5 points in node
  125. Doesn't currently support _sample_weight!
  126. """
  127. y_target = y[idxs]
  128. impurity_orig = np.mean(np.square(y_target)) * idxs.sum()
  129. # find best linear split
  130. best_impurity = impurity_orig
  131. best_linear_coef = None
  132. best_feature = None
  133. for feature_num in range(X.shape[1]):
  134. x = X[idxs, feature_num].reshape(-1, 1)
  135. m = RidgeCV(fit_intercept=False)
  136. m.fit(x, y_target)
  137. impurity = np.min(-m.best_score_) * idxs.sum()
  138. assert impurity >= 0, 'impurity should not be negative'
  139. if impurity < best_impurity:
  140. best_impurity = impurity
  141. best_linear_coef = m.coef_[0]
  142. best_feature = feature_num
  143. impurity_reduction = impurity_orig - best_impurity
  144. # no good linear fit found
  145. if impurity_reduction == 0:
  146. return Node(idxs=idxs, value=np.mean(y_target), tree_num=tree_num,
  147. feature=None, threshold=None,
  148. impurity_reduction=-1, split_or_linear='split') # leaf node that just returns its value
  149. else:
  150. assert isinstance(best_linear_coef,
  151. float), 'coef should be a float'
  152. return Node(idxs=idxs, value=best_linear_coef, tree_num=tree_num,
  153. feature=best_feature, threshold=None,
  154. impurity_reduction=impurity_reduction, split_or_linear='linear')
  155. def _construct_node_with_stump(self, X, y, idxs, tree_num, sample_weight=None, max_features=None):
  156. # array indices
  157. SPLIT = 0
  158. LEFT = 1
  159. RIGHT = 2
  160. # fit stump
  161. stump = tree.DecisionTreeRegressor(
  162. max_depth=1, max_features=max_features)
  163. if sample_weight is not None:
  164. sample_weight = sample_weight[idxs]
  165. stump.fit(X[idxs], y[idxs], sample_weight=sample_weight)
  166. # these are all arrays, arr[0] is split node
  167. # note: -2 is dummy
  168. feature = stump.tree_.feature
  169. threshold = stump.tree_.threshold
  170. impurity = stump.tree_.impurity
  171. n_node_samples = stump.tree_.n_node_samples
  172. value = stump.tree_.value
  173. # no split
  174. if len(feature) == 1:
  175. # print('no split found!', idxs.sum(), impurity, feature)
  176. return Node(idxs=idxs, value=value[SPLIT], tree_num=tree_num,
  177. feature=feature[SPLIT], threshold=threshold[SPLIT],
  178. impurity_reduction=-1, n_samples=n_node_samples)
  179. # split node
  180. impurity_reduction = (
  181. impurity[SPLIT] -
  182. impurity[LEFT] * n_node_samples[LEFT] / n_node_samples[SPLIT] -
  183. impurity[RIGHT] * n_node_samples[RIGHT] / n_node_samples[SPLIT]
  184. ) * idxs.sum()
  185. node_split = Node(idxs=idxs, value=value[SPLIT], tree_num=tree_num,
  186. feature=feature[SPLIT], threshold=threshold[SPLIT],
  187. impurity_reduction=impurity_reduction, n_samples=n_node_samples)
  188. # print('\t>>>', node_split, 'impurity', impurity, 'num_pts', idxs.sum(), 'imp_reduc', impurity_reduction)
  189. # manage children
  190. idxs_split = X[:, feature[SPLIT]] <= threshold[SPLIT]
  191. idxs_left = idxs_split & idxs
  192. idxs_right = ~idxs_split & idxs
  193. node_left = Node(idxs=idxs_left, value=value[LEFT], tree_num=tree_num)
  194. node_right = Node(
  195. idxs=idxs_right, value=value[RIGHT], tree_num=tree_num)
  196. node_split.setattrs(left_temp=node_left, right_temp=node_right, )
  197. return node_split
  198. def fit(self, X, y=None, feature_names=None, verbose=False, sample_weight=None):
  199. """
  200. Params
  201. ------
  202. _sample_weight: array-like of shape (n_samples,), default=None
  203. Sample weights. If None, then samples are equally weighted.
  204. Splits that would create child nodes with net zero or negative weight
  205. are ignored while searching for a split in each node.
  206. """
  207. if self.prediction_task == 'classification':
  208. self.classes_, y = np.unique(
  209. y, return_inverse=True) # deals with str inputs
  210. X, y = check_X_y(X, y)
  211. y = y.astype(float)
  212. if feature_names is not None:
  213. self.feature_names_ = feature_names
  214. self.trees_ = [] # list of the root nodes of added trees
  215. self.complexity_ = 0 # tracks the number of rules in the model
  216. y_predictions_per_tree = {} # predictions for each tree
  217. y_residuals_per_tree = {} # based on predictions above
  218. def _update_tree_preds(n_iter):
  219. for k in range(n_iter):
  220. for tree_num_, tree_ in enumerate(self.trees_):
  221. y_residuals_per_tree[tree_num_] = deepcopy(y)
  222. # subtract predictions of all other trees
  223. for tree_num_2_ in range(len(self.trees_)):
  224. if not tree_num_2_ == tree_num_:
  225. y_residuals_per_tree[tree_num_] -= y_predictions_per_tree[tree_num_2_]
  226. tree_.update_values(X, y_residuals_per_tree[tree_num_])
  227. y_predictions_per_tree[tree_num_] = self._predict_tree(self.trees_[
  228. tree_num_], X)
  229. # set up initial potential_splits
  230. # everything in potential_splits either is_root (so it can be added directly to self.trees_)
  231. # or it is a child of a root node that has already been added
  232. idxs = np.ones(X.shape[0], dtype=bool)
  233. node_init = self._construct_node_with_stump(X=X, y=y, idxs=idxs, tree_num=-1,
  234. sample_weight=sample_weight, max_features=self.max_features)
  235. potential_splits = [node_init]
  236. if self.include_linear and idxs.sum() >= 5:
  237. node_init_linear = self._construct_node_linear(X=X, y=y, idxs=idxs, tree_num=-1,
  238. sample_weight=sample_weight)
  239. potential_splits.append(node_init_linear)
  240. for node in potential_splits:
  241. node.setattrs(is_root=True)
  242. potential_splits = sorted(
  243. potential_splits, key=lambda x: x.impurity_reduction)
  244. # start the greedy fitting algorithm
  245. finished = False
  246. while len(potential_splits) > 0 and not finished:
  247. # print('potential_splits', [str(s) for s in potential_splits])
  248. # get node with max impurity_reduction (since it's sorted)
  249. split_node = potential_splits.pop()
  250. # don't split on node
  251. if split_node.impurity_reduction < self.min_impurity_decrease:
  252. finished = True
  253. break
  254. # split on node
  255. if verbose:
  256. print('\nadding ' + str(split_node))
  257. self.complexity_ += 1
  258. # if added a tree root
  259. if split_node.is_root:
  260. # start a new tree
  261. self.trees_.append(split_node)
  262. # update tree_num
  263. for node_ in [split_node, split_node.left_temp, split_node.right_temp]:
  264. if node_ is not None:
  265. node_.tree_num = len(self.trees_) - 1
  266. # add new root potential node
  267. node_new_root = Node(is_root=True, idxs=np.ones(X.shape[0], dtype=bool),
  268. tree_num=-1, split_or_linear=split_node.split_or_linear)
  269. potential_splits.append(node_new_root)
  270. # add children to potential splits (note this doesn't currently add linear potential splits)
  271. if split_node.split_or_linear == 'split':
  272. # assign left_temp, right_temp to be proper children
  273. # (basically adds them to tree in predict method)
  274. split_node.setattrs(left=split_node.left_temp,
  275. right=split_node.right_temp)
  276. # add children to potential_splits
  277. potential_splits.append(split_node.left)
  278. potential_splits.append(split_node.right)
  279. # update predictions for altered tree
  280. for tree_num_ in range(len(self.trees_)):
  281. y_predictions_per_tree[tree_num_] = self._predict_tree(self.trees_[
  282. tree_num_], X)
  283. # dummy 0 preds for possible new trees
  284. y_predictions_per_tree[-1] = np.zeros(X.shape[0])
  285. # update residuals for each tree
  286. # -1 is key for potential new tree
  287. for tree_num_ in list(range(len(self.trees_))) + [-1]:
  288. y_residuals_per_tree[tree_num_] = deepcopy(y)
  289. # subtract predictions of all other trees
  290. for tree_num_2_ in range(len(self.trees_)):
  291. if not tree_num_2_ == tree_num_:
  292. y_residuals_per_tree[tree_num_] -= y_predictions_per_tree[tree_num_2_]
  293. _update_tree_preds(self.k1)
  294. # recompute all impurities + update potential_split children
  295. potential_splits_new = []
  296. for potential_split in potential_splits:
  297. y_target = y_residuals_per_tree[potential_split.tree_num]
  298. if potential_split.split_or_linear == 'split':
  299. # re-calculate the best split
  300. potential_split_updated = self._construct_node_with_stump(X=X,
  301. y=y_target,
  302. idxs=potential_split.idxs,
  303. tree_num=potential_split.tree_num,
  304. sample_weight=sample_weight,
  305. max_features=self.max_features)
  306. # need to preserve certain attributes from before (value at this split + is_root)
  307. # value may change because residuals may have changed, but we want it to store the value from before
  308. potential_split.setattrs(
  309. feature=potential_split_updated.feature,
  310. threshold=potential_split_updated.threshold,
  311. impurity_reduction=potential_split_updated.impurity_reduction,
  312. left_temp=potential_split_updated.left_temp,
  313. right_temp=potential_split_updated.right_temp,
  314. )
  315. elif potential_split.split_or_linear == 'linear':
  316. assert potential_split.is_root, 'Currently, linear node only supported as root'
  317. assert potential_split.idxs.sum(
  318. ) == X.shape[0], 'Currently, linear node only supported as root'
  319. potential_split_updated = self._construct_node_linear(idxs=potential_split.idxs,
  320. X=X,
  321. y=y_target,
  322. tree_num=potential_split.tree_num,
  323. sample_weight=sample_weight)
  324. # don't need to retain anything from before (besides maybe is_root)
  325. potential_split.setattrs(
  326. feature=potential_split_updated.feature,
  327. impurity_reduction=potential_split_updated.impurity_reduction,
  328. value=potential_split_updated.value,
  329. )
  330. # this is a valid split
  331. if potential_split.impurity_reduction is not None:
  332. potential_splits_new.append(potential_split)
  333. # sort so largest impurity reduction comes last (should probs make this a heap later)
  334. potential_splits = sorted(
  335. potential_splits_new, key=lambda x: x.impurity_reduction)
  336. if verbose:
  337. print(self)
  338. if self.max_rules is not None and self.complexity_ >= self.max_rules:
  339. finished = True
  340. break
  341. _update_tree_preds(self.k2)
  342. # potentially fit linear model on the tree preds
  343. if self.posthoc_ridge:
  344. if self.prediction_task == 'regression':
  345. self.weighted_model_ = RidgeCV(
  346. alphas=(0.01, 0.1, 0.5, 1.0, 5, 10))
  347. elif self.prediction_task == 'classification':
  348. self.weighted_model_ = RidgeClassifierCV(
  349. alphas=(0.01, 0.1, 0.5, 1.0, 5, 10))
  350. X_feats = self._extract_tree_predictions(X)
  351. self.weighted_model_.fit(X_feats, y)
  352. return self
  353. def _tree_to_str(self, root: Node, prefix=''):
  354. if root is None:
  355. return ''
  356. elif root.split_or_linear == 'linear':
  357. return prefix + str(root)
  358. elif root.threshold is None:
  359. return ''
  360. pprefix = prefix + '\t'
  361. return prefix + str(root) + '\n' + self._tree_to_str(root.left, pprefix) + self._tree_to_str(root.right,
  362. pprefix)
  363. def __str__(self):
  364. s = '------------\n' + \
  365. '\n\t+\n'.join([self._tree_to_str(t) for t in self.trees_])
  366. if hasattr(self, 'feature_names_') and self.feature_names_ is not None:
  367. for i in range(len(self.feature_names_))[::-1]:
  368. s = s.replace(f'X_{i}', self.feature_names_[i])
  369. return s
  370. def predict(self, X):
  371. if self.posthoc_ridge and self.weighted_model_: # note, during fitting don't use the weighted moel
  372. X_feats = self._extract_tree_predictions(X)
  373. return self.weighted_model_.predict(X_feats)
  374. preds = np.zeros(X.shape[0])
  375. for tree in self.trees_:
  376. preds += self._predict_tree(tree, X)
  377. if self.prediction_task == 'regression':
  378. return preds
  379. elif self.prediction_task == 'classification':
  380. return (preds > 0.5).astype(int)
  381. def predict_proba(self, X):
  382. if self.prediction_task == 'regression':
  383. return NotImplemented
  384. elif self.posthoc_ridge and self.weighted_model_: # note, during fitting don't use the weighted moel
  385. X_feats = self._extract_tree_predictions(X)
  386. d = self.weighted_model_.decision_function(
  387. X_feats) # for 2 classes, this (n_samples,)
  388. probs = np.exp(d) / (1 + np.exp(d))
  389. return np.vstack((1 - probs, probs)).transpose()
  390. else:
  391. preds = np.zeros(X.shape[0])
  392. for tree in self.trees_:
  393. preds += self._predict_tree(tree, X)
  394. # constrain to range of probabilities
  395. preds = np.clip(preds, a_min=0., a_max=1.)
  396. return np.vstack((1 - preds, preds)).transpose()
  397. def _extract_tree_predictions(self, X):
  398. """Extract predictions for all trees
  399. """
  400. X_feats = np.zeros((X.shape[0], len(self.trees_)))
  401. for tree_num_ in range(len(self.trees_)):
  402. preds_tree = self._predict_tree(self.trees_[tree_num_], X)
  403. X_feats[:, tree_num_] = preds_tree
  404. return X_feats
  405. def _predict_tree(self, root: Node, X):
  406. """Predict for a single tree
  407. This can be made way faster
  408. """
  409. def _predict_tree_single_point(root: Node, x):
  410. if root.split_or_linear == 'linear':
  411. return x[root.feature] * root.value
  412. elif root.left is None and root.right is None:
  413. return root.value
  414. left = x[root.feature] <= root.threshold
  415. if left:
  416. if root.left is None: # we don't actually have to worry about this case
  417. return root.value
  418. else:
  419. return _predict_tree_single_point(root.left, x)
  420. else:
  421. if root.right is None: # we don't actually have to worry about this case
  422. return root.value
  423. else:
  424. return _predict_tree_single_point(root.right, x)
  425. preds = np.zeros(X.shape[0])
  426. for i in range(X.shape[0]):
  427. preds[i] = _predict_tree_single_point(root, X[i])
  428. return preds
  429. def plot(self, cols=2, feature_names=None, filename=None, label="all",
  430. impurity=False, tree_number=None, dpi=150, fig_size=None):
  431. is_single_tree = len(self.trees_) < 2 or tree_number is not None
  432. n_cols = int(cols)
  433. n_rows = int(np.ceil(len(self.trees_) / n_cols))
  434. # if is_single_tree:
  435. # fig, ax = plt.subplots(1)
  436. # else:
  437. # fig, axs = plt.subplots(n_rows, n_cols)
  438. n_plots = int(len(self.trees_)) if tree_number is None else 1
  439. fig, axs = plt.subplots(n_plots, dpi=dpi)
  440. if fig_size is not None:
  441. fig.set_size_inches(fig_size, fig_size)
  442. criterion = "squared_error" if self.prediction_task == "regression" else "gini"
  443. n_classes = 1 if self.prediction_task == 'regression' else 2
  444. ax_size = int(len(self.trees_)) # n_cols * n_rows
  445. for i in range(n_plots):
  446. r = i // n_cols
  447. c = i % n_cols
  448. if not is_single_tree:
  449. # ax = axs[r, c]
  450. ax = axs[i]
  451. else:
  452. ax = axs
  453. try:
  454. dt = extract_sklearn_tree_from_figs(
  455. self, i if tree_number is None else tree_number, n_classes)
  456. plot_tree(dt, ax=ax, feature_names=feature_names,
  457. label=label, impurity=impurity)
  458. except IndexError:
  459. ax.axis('off')
  460. continue
  461. ax.set_title(f"Tree {i}")
  462. if filename is not None:
  463. plt.savefig(filename)
  464. return
  465. plt.show()
  466. class FIGSExtRegressor(FIGSExt):
  467. def _init_prediction_task(self):
  468. self.prediction_task = 'regression'
  469. class FIGSExtClassifier(FIGSExt):
  470. def _init_prediction_task(self):
  471. self.prediction_task = 'classification'
  472. if __name__ == '__main__':
  473. np.random.seed(13)
  474. # X, y = datasets.load_breast_cancer(return_X_y=True) # binary classification
  475. X, y = datasets.load_diabetes(return_X_y=True) # regression
  476. # X = np.random.randn(500, 10)
  477. # y = (X[:, 0] > 0).astype(float) + (X[:, 1] > 1).astype(float)
  478. X_train, X_test, y_train, y_test = train_test_split(
  479. X, y, test_size=0.33, random_state=42
  480. )
  481. print('X.shape', X.shape)
  482. print('ys', np.unique(y_train), '\n\n')
  483. m = FIGSExtClassifier(max_rules=50)
  484. m.fit(X_train, y_train)
  485. print(m.predict_proba(X_train))
  486. m.plot(2, tree_number=0)
Tip!

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

Comments

Loading...