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_gam.py 16 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
  1. from copy import deepcopy
  2. import numpy as np
  3. import pandas as pd
  4. from sklearn.base import BaseEstimator
  5. from sklearn.linear_model import ElasticNetCV, LinearRegression, RidgeCV
  6. from sklearn.tree import DecisionTreeRegressor
  7. from sklearn.utils.validation import check_is_fitted
  8. from sklearn.utils import check_array
  9. from sklearn.utils.multiclass import check_classification_targets
  10. from sklearn.utils.validation import check_X_y
  11. from sklearn.utils.validation import _check_sample_weight
  12. from sklearn.ensemble import GradientBoostingClassifier, GradientBoostingRegressor
  13. from sklearn.model_selection import train_test_split
  14. from sklearn.metrics import accuracy_score, roc_auc_score
  15. from tqdm import tqdm
  16. import imodels
  17. from sklearn.base import RegressorMixin, ClassifierMixin
  18. class TreeGAM(BaseEstimator):
  19. """Tree-based GAM classifier.
  20. Uses cyclical boosting to fit a GAM with small trees.
  21. Simplified version of the explainable boosting machine described in https://github.com/interpretml/interpret
  22. Only works for binary classification.
  23. Fits a scalar bias to the mean.
  24. """
  25. def __init__(
  26. self,
  27. n_boosting_rounds=100,
  28. max_leaf_nodes=3,
  29. reg_param=0.0,
  30. learning_rate: float = 0.01,
  31. n_boosting_rounds_marginal=0,
  32. max_leaf_nodes_marginal=2,
  33. reg_param_marginal=0.0,
  34. fit_linear_marginal=None,
  35. select_linear_marginal=False,
  36. decay_rate_towards_marginal=1.0,
  37. fit_posthoc_tree_coefs=None,
  38. boosting_strategy="cyclic",
  39. validation_frac=0.15,
  40. random_state=None,
  41. ):
  42. """
  43. Params
  44. ------
  45. n_boosting_rounds : int
  46. Number of boosting rounds for the cyclic boosting.
  47. max_leaf_nodes : int
  48. Maximum number of leaf nodes for the trees in the cyclic boosting.
  49. reg_param : float
  50. Regularization parameter for the cyclic boosting.
  51. learning_rate: float
  52. Learning rate for the cyclic boosting.
  53. n_boosting_rounds_marginal : int
  54. Number of boosting rounds for the marginal boosting.
  55. max_leaf_nodes_marginal : int
  56. Maximum number of leaf nodes for the trees in the marginal boosting.
  57. reg_param_marginal : float
  58. Regularization parameter for the marginal boosting.
  59. fit_linear_marginal : str [None, "None", "ridge", "NNLS"]
  60. Whether to fit a linear model to the marginal effects.
  61. NNLS for non-negative least squares
  62. ridge for ridge regression
  63. None for no linear model
  64. select_linear_marginal: bool
  65. Whether to restrict features to those with non-negative coefficients in the linear model.
  66. Requires that fit_linear_marginal is NNLS.
  67. decay_rate_towards_marginal: float, [0, 1]
  68. Decay rate for regularizing each shape function towards the marginal shape function after each step
  69. 1 means no decay, 0 means only use marginal effects
  70. shape = (1 - decay_rate_towards_marginal) * shape + decay_rate_towards_marginal * marginal_shape
  71. The way this is implemented is by keeping track of how many times to multiply decay_rate_towards_marginal for each cyclic estimator
  72. fit_posthoc_tree_coefs: str [None, "ridge"]
  73. Whether to fit a linear model to the tree coefficients after fitting the cyclic boosting.
  74. boosting_strategy : str ["cyclic", "greedy"]
  75. Whether to use cyclic boosting (cycle over features) or greedy boosting (select best feature at each step)
  76. validation_frac: float
  77. Fraction of data to use for early stopping.
  78. random_state : int
  79. Random seed.
  80. """
  81. self.n_boosting_rounds = n_boosting_rounds
  82. self.max_leaf_nodes = max_leaf_nodes
  83. self.reg_param = reg_param
  84. self.learning_rate = learning_rate
  85. self.max_leaf_nodes_marginal = max_leaf_nodes_marginal
  86. self.reg_param_marginal = reg_param_marginal
  87. self.n_boosting_rounds_marginal = n_boosting_rounds_marginal
  88. self.fit_linear_marginal = fit_linear_marginal
  89. self.select_linear_marginal = select_linear_marginal
  90. self.decay_rate_towards_marginal = decay_rate_towards_marginal
  91. self.fit_posthoc_tree_coefs = fit_posthoc_tree_coefs
  92. self.boosting_strategy = boosting_strategy
  93. self.validation_frac = validation_frac
  94. self.random_state = random_state
  95. def fit(self, X, y, sample_weight=None):
  96. X, y = check_X_y(X, y, accept_sparse=False, multi_output=False)
  97. if isinstance(self, ClassifierMixin):
  98. check_classification_targets(y)
  99. self.classes_, y = np.unique(y, return_inverse=True)
  100. sample_weight = _check_sample_weight(sample_weight, X, dtype=None)
  101. # split into train and validation for early stopping
  102. (
  103. X_train,
  104. X_val,
  105. y_train,
  106. y_val,
  107. sample_weight_train,
  108. sample_weight_val,
  109. ) = train_test_split(
  110. X,
  111. y,
  112. sample_weight,
  113. test_size=self.validation_frac,
  114. random_state=self.random_state,
  115. stratify=y if isinstance(self, ClassifierMixin) else None,
  116. )
  117. self.estimators_marginal = []
  118. self.estimators_ = []
  119. self.bias_ = np.mean(y)
  120. if self.n_boosting_rounds_marginal > 0:
  121. self._marginal_fit(
  122. X_train,
  123. y_train,
  124. sample_weight_train,
  125. )
  126. if self.n_boosting_rounds > 0:
  127. self._cyclic_boost(
  128. X_train,
  129. y_train,
  130. sample_weight_train,
  131. X_val,
  132. y_val,
  133. sample_weight_val,
  134. )
  135. if self.fit_posthoc_tree_coefs is not None:
  136. self._fit_posthoc_tree_coefs(X_train, y_train, sample_weight_train)
  137. self.mse_val_ = self._calc_mse(X_val, y_val, sample_weight_val)
  138. return self
  139. def _marginal_fit(
  140. self,
  141. X_train,
  142. y_train,
  143. sample_weight_train,
  144. ):
  145. """Fit a gbdt estimator for each feature independently.
  146. Store in self.estimators_marginal"""
  147. residuals_train = y_train - self.predict_proba(X_train)[:, 1]
  148. p = X_train.shape[1]
  149. for feature_num in range(p):
  150. X_ = np.zeros_like(X_train)
  151. X_[:, feature_num] = X_train[:, feature_num]
  152. est = GradientBoostingRegressor(
  153. max_leaf_nodes=self.max_leaf_nodes_marginal,
  154. random_state=self.random_state,
  155. n_estimators=self.n_boosting_rounds_marginal,
  156. )
  157. est.fit(X_, residuals_train, sample_weight=sample_weight_train)
  158. if self.reg_param_marginal > 0:
  159. est = imodels.HSTreeRegressor(
  160. est, reg_param=self.reg_param_marginal)
  161. self.estimators_marginal.append(est)
  162. if (
  163. self.fit_linear_marginal is not None
  164. and not self.fit_linear_marginal == "None"
  165. ):
  166. if self.fit_linear_marginal.lower() == "ridge":
  167. linear_marginal = RidgeCV(fit_intercept=False)
  168. elif self.fit_linear_marginal == "NNLS":
  169. linear_marginal = LinearRegression(
  170. fit_intercept=False, positive=True)
  171. linear_marginal.fit(
  172. np.array([est.predict(X_train)
  173. for est in self.estimators_marginal]).T,
  174. residuals_train,
  175. sample_weight_train,
  176. )
  177. self.marginal_coef_ = linear_marginal.coef_
  178. self.lin = linear_marginal
  179. else:
  180. self.marginal_coef_ = np.ones(p) / p
  181. def _cyclic_boost(
  182. self, X_train, y_train, sample_weight_train, X_val, y_val, sample_weight_val
  183. ):
  184. """Apply cyclic boosting, storing trees in self.estimators_"""
  185. residuals_train = y_train - self.predict_proba(X_train)[:, 1]
  186. mse_val = self._calc_mse(X_val, y_val, sample_weight_val)
  187. self.decay_coef_towards_marginal_ = []
  188. for _ in range(self.n_boosting_rounds):
  189. boosting_round_ests = []
  190. boosting_round_mses = []
  191. feature_nums = np.arange(X_train.shape[1])
  192. if self.select_linear_marginal:
  193. assert (
  194. self.fit_linear_marginal == "NNLS"
  195. and self.n_boosting_rounds_marginal > 0
  196. ), "select_linear_marginal requires fit_linear_marginal to be NNLS and for n_boosting_rounds_marginal > 0"
  197. feature_nums = np.where(self.marginal_coef_ > 0)[0]
  198. for feature_num in feature_nums:
  199. X_ = np.zeros_like(X_train)
  200. X_[:, feature_num] = X_train[:, feature_num]
  201. est = DecisionTreeRegressor(
  202. max_leaf_nodes=self.max_leaf_nodes,
  203. random_state=self.random_state,
  204. )
  205. est.fit(X_, residuals_train, sample_weight=sample_weight_train)
  206. succesfully_split_on_feature = np.all(
  207. (est.tree_.feature[0] == feature_num) | (
  208. est.tree_.feature[0] == -2)
  209. )
  210. if not succesfully_split_on_feature:
  211. continue
  212. if self.reg_param > 0:
  213. est = imodels.HSTreeRegressor(
  214. est, reg_param=self.reg_param)
  215. self.estimators_.append(est)
  216. residuals_train_new = (
  217. residuals_train - self.learning_rate * est.predict(X_train)
  218. )
  219. if self.boosting_strategy == "cyclic":
  220. residuals_train = residuals_train_new
  221. elif self.boosting_strategy == "greedy":
  222. mse_train_new = self._calc_mse(
  223. X_train, y_train, sample_weight_train
  224. )
  225. # don't add each estimator for greedy
  226. boosting_round_ests.append(
  227. deepcopy(self.estimators_.pop()))
  228. boosting_round_mses.append(mse_train_new)
  229. if self.boosting_strategy == "greedy":
  230. best_est = boosting_round_ests[np.argmin(boosting_round_mses)]
  231. self.estimators_.append(best_est)
  232. residuals_train = (
  233. residuals_train - self.learning_rate *
  234. best_est.predict(X_train)
  235. )
  236. # decay marginal effects
  237. if self.decay_rate_towards_marginal < 1.0:
  238. new_decay_coefs = [self.decay_rate_towards_marginal] * (
  239. len(self.estimators_) -
  240. len(self.decay_coef_towards_marginal_)
  241. )
  242. # print(self.decay_coef_towards_marginal_)
  243. # print('new_decay_coefs', new_decay_coefs)
  244. self.decay_coef_towards_marginal_ = [
  245. x * self.decay_rate_towards_marginal
  246. for x in self.decay_coef_towards_marginal_
  247. ] + new_decay_coefs
  248. # print(self.decay_coef_towards_marginal_)
  249. # early stopping if validation error does not decrease
  250. mse_val_new = self._calc_mse(X_val, y_val, sample_weight_val)
  251. if mse_val_new >= mse_val:
  252. # print("early stop!")
  253. return
  254. else:
  255. mse_val = mse_val_new
  256. def _fit_posthoc_tree_coefs(self, X, y, sample_weight=None):
  257. # extract predictions from each tree
  258. X_pred_tree = np.array([est.predict(X) for est in self.estimators_]).T
  259. print('shapes', X.shape, X_pred_tree.shape,
  260. y.shape, len(self.estimators_))
  261. coef_prior = np.ones(len(self.estimators_)) * self.learning_rate
  262. y = y - self.bias_ - X_pred_tree @ coef_prior
  263. if self.fit_posthoc_tree_coefs.lower() == "ridge":
  264. m = RidgeCV(fit_intercept=False)
  265. elif self.fit_posthoc_tree_coefs.lower() == "nnls":
  266. m = LinearRegression(fit_intercept=False, positive=True)
  267. elif self.fit_posthoc_tree_coefs.lower() == "elasticnet":
  268. m = ElasticNetCV(fit_intercept=False, positive=True)
  269. m.fit(X_pred_tree, y, sample_weight=sample_weight)
  270. self.cyclic_coef_ = m.coef_ + coef_prior
  271. def predict_proba(self, X, marginal_only=False):
  272. """
  273. Params
  274. ------
  275. marginal_only: bool
  276. If True, only use the marginal effects.
  277. """
  278. X = check_array(X, accept_sparse=False, dtype=None)
  279. check_is_fitted(self)
  280. probs1 = np.ones(X.shape[0]) * self.bias_
  281. # marginal prediction
  282. for i, est in enumerate(self.estimators_marginal):
  283. probs1 += est.predict(X) * self.marginal_coef_[i]
  284. # cyclic coefs prediction
  285. if not marginal_only:
  286. if not hasattr(self, "cyclic_coef_"):
  287. cyclic_coef_ = np.ones(
  288. len(self.estimators_)) * self.learning_rate
  289. else:
  290. cyclic_coef_ = self.cyclic_coef_
  291. # print('coef', cyclic_coef_)
  292. if self.decay_rate_towards_marginal < 1.0:
  293. for i, est in enumerate(self.estimators_):
  294. if i < len(self.decay_coef_towards_marginal_):
  295. probs1 += (
  296. cyclic_coef_[i]
  297. * self.decay_coef_towards_marginal_[i]
  298. * est.predict(X)
  299. )
  300. else:
  301. probs1 += cyclic_coef_[i] * est.predict(X)
  302. else:
  303. for i, est in enumerate(self.estimators_):
  304. probs1 += cyclic_coef_[i] * est.predict(X)
  305. probs1 = np.clip(probs1, a_min=0, a_max=1)
  306. return np.array([1 - probs1, probs1]).T
  307. def predict(self, X, marginal_only=False):
  308. if isinstance(self, RegressorMixin):
  309. return self.predict_proba(X, marginal_only=marginal_only)[:, 1]
  310. elif isinstance(self, ClassifierMixin):
  311. return np.argmax(self.predict_proba(X, marginal_only=marginal_only), axis=1)
  312. def _calc_mse(self, X, y, sample_weight=None):
  313. return np.average(
  314. np.square(y - self.predict_proba(X)[:, 1]),
  315. weights=sample_weight,
  316. )
  317. class TreeGAMRegressor(TreeGAM, RegressorMixin):
  318. ...
  319. class TreeGAMClassifier(TreeGAM, ClassifierMixin):
  320. ...
  321. if __name__ == "__main__":
  322. X, y, feature_names = imodels.get_clean_dataset("heart")
  323. X, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
  324. gam = TreeGAMClassifier(
  325. boosting_strategy="cyclic",
  326. random_state=42,
  327. learning_rate=0.1,
  328. max_leaf_nodes=3,
  329. # select_linear_marginal=True,
  330. # fit_linear_marginal="NNLS",
  331. # n_boosting_rounds_marginal=3,
  332. # decay_rate_towards_marginal=0,
  333. fit_posthoc_tree_coefs="elasticnet",
  334. n_boosting_rounds=100,
  335. )
  336. gam.fit(X, y_train)
  337. # check roc auc score
  338. y_pred = gam.predict_proba(X_test)[:, 1]
  339. # print(
  340. # "train roc:",
  341. # roc_auc_score(y_train, gam.predict_proba(X)[:, 1]).round(3),
  342. # )
  343. print("test roc:", roc_auc_score(y_test, y_pred).round(3))
  344. print("test acc:", accuracy_score(y_test, gam.predict(X_test)).round(3))
  345. print('\t(imb:', np.mean(y_test).round(3), ')')
  346. # print(
  347. # "accs",
  348. # accuracy_score(y_train, gam.predict(X)).round(3),
  349. # accuracy_score(y_test, gam.predict(X_test)).round(3),
  350. # "imb",
  351. # np.mean(y_train).round(3),
  352. # np.mean(y_test).round(3),
  353. # )
  354. # # print(gam.estimators_)
Tip!

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

Comments

Loading...