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

gam_multitask.py 14 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
  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, LassoCV, LogisticRegressionCV
  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, AdaBoostClassifier, AdaBoostRegressor
  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. from sklearn.multioutput import MultiOutputRegressor, MultiOutputClassifier
  17. from collections import defaultdict
  18. import pandas as pd
  19. import json
  20. from sklearn.preprocessing import StandardScaler
  21. from imodels.util.transforms import CorrelationScreenTransformer
  22. import imodels
  23. from interpret.glassbox import ExplainableBoostingClassifier, ExplainableBoostingRegressor
  24. from sklearn.base import RegressorMixin, ClassifierMixin
  25. # See notes on EBM in the docs
  26. # main file: https://github.com/interpretml/interpret/blob/develop/python/interpret-core/interpret/glassbox/_ebm/_ebm.py
  27. # merge ebms: https://github.com/interpretml/interpret/blob/develop/python/interpret-core/interpret/glassbox/_ebm/_merge_ebms.py#L280
  28. # eval_terms: https://interpret.ml/docs/python/api/ExplainableBoostingRegressor.html#interpret.glassbox.ExplainableBoostingRegressor.eval_terms
  29. class MultiTaskGAM(BaseEstimator):
  30. """EBM-based GAM that shares curves for predicting different outputs.
  31. - If only one target is given, we fit an EBM to predict each covariate
  32. - If multiple targets are given, we fit a an EBM to predict each target
  33. - If only one target is given and use_single_task_with_reweighting, we fit an EBM to predict the single target, then apply reweighting
  34. """
  35. def __init__(
  36. self,
  37. ebm_kwargs={'n_jobs': 1, 'max_rounds': 5000, },
  38. multitask=True,
  39. interactions=0.95,
  40. linear_penalty='ridge',
  41. onehot_prior=False,
  42. renormalize_features=False,
  43. use_normalize_feature_targets=False,
  44. use_internal_classifiers=False,
  45. fit_target_curves=True,
  46. use_correlation_screening_for_features=False,
  47. use_single_task_with_reweighting=False,
  48. fit_linear_frac: float = None,
  49. random_state=42,
  50. ):
  51. """
  52. Params
  53. ------
  54. Note: args override ebm_kwargs if there are duplicates
  55. one_hot_prior: bool
  56. If True and multitask, the linear model will be fit with a prior that the ebm
  57. features predicting the target should have coef 1
  58. renormalize_features: bool
  59. If True, renormalize the features before fitting the linear model
  60. use_normalize_feature_targets: bool
  61. whether to normalize the features used as targets for internal EBMs
  62. (does not apply to target columns)
  63. If input features are normalized already, this has no effect
  64. use_internal_classifiers: bool
  65. whether to use internal classifiers (as opposed to regressors)
  66. fit_target_curves: bool
  67. whether to fit an EBM to predict the target
  68. use_single_task_with_reweighting: bool
  69. fit an EBM to predict the single target, then apply linear reweighting
  70. use_correlation_screening_for_features: bool
  71. whether to use correlation screening for features
  72. fit_linear_frac: float
  73. If not None, the fraction of features to use for the linear model (the rest are used for the EBM)
  74. """
  75. self.ebm_kwargs = ebm_kwargs
  76. self.multitask = multitask
  77. self.linear_penalty = linear_penalty
  78. self.random_state = random_state
  79. self.interactions = interactions
  80. self.onehot_prior = onehot_prior
  81. self.use_normalize_feature_targets = use_normalize_feature_targets
  82. self.renormalize_features = renormalize_features
  83. self.use_internal_classifiers = use_internal_classifiers
  84. self.fit_target_curves = fit_target_curves
  85. self.use_single_task_with_reweighting = use_single_task_with_reweighting
  86. self.use_correlation_screening_for_features = use_correlation_screening_for_features
  87. self.fit_linear_frac = fit_linear_frac
  88. # override ebm_kwargs
  89. ebm_kwargs['random_state'] = random_state
  90. ebm_kwargs['interactions'] = interactions
  91. def fit(self, X, y, sample_weight=None):
  92. X, y = check_X_y(X, y, accept_sparse=False, multi_output=True)
  93. self.n_outputs_ = 1 if len(y.shape) == 1 else y.shape[1]
  94. if self.n_outputs_ > 1 and not self.fit_target_curves:
  95. raise ValueError(
  96. "fit_target_curves must be True when n_outputs > 1")
  97. if isinstance(self, ClassifierMixin):
  98. check_classification_targets(y)
  99. if self.n_outputs_ == 1:
  100. self.classes_, y = np.unique(y, return_inverse=True)
  101. if len(self.classes_) > 2:
  102. raise ValueError(
  103. "MultiTaskGAMClassifier currently only supports binary classification")
  104. elif self.n_outputs_ > 1:
  105. self.classes_ = [np.unique(y[:, i])
  106. for i in range(self.n_outputs_)]
  107. if any(len(c) > 2 for c in self.classes_):
  108. raise ValueError(
  109. "MultiTaskGAMClassifier currently only supports binary classification")
  110. sample_weight = _check_sample_weight(sample_weight, X, dtype=None)
  111. if self.use_single_task_with_reweighting:
  112. assert self.n_outputs_ == 1, "use_single_task_with_reweighting only works with one output"
  113. assert self.multitask, "use_single_task_with_reweighting only works with multitask"
  114. # just fit ebm normally
  115. if not self.multitask:
  116. if isinstance(self, ClassifierMixin):
  117. self.ebm_ = ExplainableBoostingClassifier(**self.ebm_kwargs)
  118. else:
  119. self.ebm_ = ExplainableBoostingRegressor(**self.ebm_kwargs)
  120. # fit
  121. if self.n_outputs_ > 1:
  122. if isinstance(self, ClassifierMixin):
  123. self.ebm_multioutput_ = MultiOutputClassifier(self.ebm_)
  124. else:
  125. self.ebm_multioutput_ = MultiOutputRegressor(self.ebm_)
  126. self.ebm_multioutput_.fit(X, y, sample_weight=sample_weight)
  127. else:
  128. self.ebm_.fit(X, y, sample_weight=sample_weight)
  129. return self
  130. # fit EBM(s)
  131. self.ebms_ = []
  132. num_samples, num_features = X.shape
  133. idxs_ebm, idxs_lin = self._split_data(num_samples)
  134. # fit EBM
  135. if self.use_single_task_with_reweighting:
  136. # fit an EBM to predict the single output
  137. self.ebms_.append(self._initialize_ebm_internal(y[idxs_ebm]))
  138. self.ebms_[-1].fit(X[idxs_ebm], y[idxs_ebm],
  139. sample_weight=sample_weight[idxs_ebm])
  140. elif self.n_outputs_ == 1:
  141. # with 1 output, we fit an EBM to each feature
  142. for task_num in tqdm(range(num_features)):
  143. y_ = np.ascontiguousarray(X[idxs_ebm][:, task_num])
  144. X_ = deepcopy(X[idxs_ebm])
  145. X_[:, task_num] = 0
  146. self.ebms_.append(self._initialize_ebm_internal(y_))
  147. if isinstance(self, ClassifierMixin):
  148. _, y_ = np.unique(y_, return_inverse=True)
  149. elif self.use_normalize_feature_targets:
  150. y_ = StandardScaler().fit_transform(y_.reshape(-1, 1)).ravel()
  151. self.ebms_[task_num].fit(
  152. X_, y_, sample_weight=sample_weight[idxs_ebm])
  153. # also fit an EBM to the target
  154. if self.fit_target_curves:
  155. self.ebms_.append(self._initialize_ebm_internal(y[idxs_ebm]))
  156. self.ebms_[num_features].fit(
  157. X[idxs_ebm], y[idxs_ebm], sample_weight=sample_weight[idxs_ebm])
  158. elif self.n_outputs_ > 1:
  159. # with multiple outputs, we fit an EBM to each output
  160. for task_num in tqdm(range(self.n_outputs_)):
  161. self.ebms_.append(self._initialize_ebm_internal(y[idxs_ebm]))
  162. y_ = np.ascontiguousarray(y[idxs_ebm][:, task_num])
  163. self.ebms_[task_num].fit(
  164. X[idxs_ebm], y_, sample_weight=sample_weight[idxs_ebm])
  165. # extract features from EBMs
  166. self.term_names_list_ = [
  167. ebm_.term_names_ for ebm_ in self.ebms_]
  168. self.term_names_ = sum(self.term_names_list_, [])
  169. feats = self._extract_ebm_features(X)
  170. if self.renormalize_features:
  171. self.scaler_ = StandardScaler()
  172. feats = self.scaler_.fit_transform(feats)
  173. if self.use_correlation_screening_for_features:
  174. self.correlation_screener_ = CorrelationScreenTransformer()
  175. feats = self.correlation_screener_.fit_transform(feats, y)
  176. feats[np.isinf(feats)] = 0
  177. # fit linear model
  178. self.lin_model = self._fit_linear_model(
  179. feats[idxs_lin], y[idxs_lin], sample_weight[idxs_lin])
  180. return self
  181. def _initialize_ebm_internal(self, y):
  182. if self.use_internal_classifiers and len(np.unique(y)) == 2:
  183. return ExplainableBoostingClassifier(**self.ebm_kwargs)
  184. else:
  185. return ExplainableBoostingRegressor(**self.ebm_kwargs)
  186. def _split_data(self, num_samples):
  187. '''Split data into EBM and linear model data
  188. '''
  189. if self.fit_linear_frac is not None:
  190. rng = np.random.RandomState(self.random_state)
  191. idxs_ebm = rng.choice(num_samples, int(
  192. num_samples * self.fit_linear_frac), replace=False)
  193. idxs_lin = np.array(
  194. [i for i in range(num_samples) if i not in idxs_ebm])
  195. else:
  196. idxs_ebm = np.arange(num_samples)
  197. idxs_lin = idxs_ebm
  198. assert len(idxs_ebm) > 0, f"No data for EBM! {self.fit_linear_frac=}"
  199. assert len(
  200. idxs_lin) > 0, f"No data for linear model! {self.fit_linear_frac=}"
  201. return idxs_ebm, idxs_lin
  202. def _fit_linear_model(self, feats, y, sample_weight):
  203. # fit a linear model to the features
  204. if isinstance(self, ClassifierMixin):
  205. lin_model = {
  206. 'ridge': LogisticRegressionCV(penalty='l2'),
  207. 'elasticnet': LogisticRegressionCV(penalty='elasticnet'),
  208. 'lasso': LogisticRegressionCV(penalty='l1'),
  209. }[self.linear_penalty]
  210. if self.n_outputs_ > 1:
  211. lin_model = MultiOutputClassifier(lin_model)
  212. else:
  213. lin_model = {
  214. 'ridge': RidgeCV(alphas=np.logspace(-2, 3, 7)),
  215. 'elasticnet': ElasticNetCV(n_alphas=7),
  216. 'lasso': LassoCV(n_alphas=7),
  217. }[self.linear_penalty]
  218. # onehot prior is a prior (for regression only) that
  219. # the ebm features predicting the target should have coef 1
  220. if not self.onehot_prior or isinstance(self, ClassifierMixin):
  221. lin_model.fit(feats, y, sample_weight=sample_weight)
  222. else:
  223. coef_prior_ = np.zeros((feats.shape[1], ))
  224. coef_prior_[:-len(self.term_names_list_[-1])] = 1
  225. preds_prior = feats @ coef_prior_
  226. residuals = y - preds_prior
  227. lin_model.fit(feats, residuals, sample_weight=sample_weight)
  228. lin_model.coef_ = lin_model.coef_ + coef_prior_
  229. return lin_model
  230. def _extract_ebm_features(self, X):
  231. '''
  232. Extract features by extracting all terms with EBM
  233. '''
  234. feats = np.empty((X.shape[0], len(self.term_names_)))
  235. offset = 0
  236. for ebm_num in range(len(self.ebms_)):
  237. n_features_ebm_num = len(self.term_names_list_[ebm_num])
  238. feats[:, offset: offset + n_features_ebm_num] = \
  239. self.ebms_[ebm_num].eval_terms(X)
  240. offset += n_features_ebm_num
  241. return feats
  242. def predict(self, X):
  243. check_is_fitted(self)
  244. X = check_array(X, accept_sparse=False)
  245. if hasattr(self, 'ebms_'):
  246. feats = self._extract_ebm_features(X)
  247. if hasattr(self, 'scaler_'):
  248. feats = self.scaler_.transform(feats)
  249. if hasattr(self, 'correlation_screener_'):
  250. feats = self.correlation_screener_.transform(feats)
  251. feats[np.isinf(feats)] = 0
  252. return self.lin_model.predict(feats)
  253. # multi-output without multitask learning
  254. elif hasattr(self, 'ebm_multioutput_'):
  255. return self.ebm_multioutput_.predict(X)
  256. # single-task standard
  257. elif hasattr(self, 'ebm_'):
  258. return self.ebm_.predict(X)
  259. def predict_proba(self, X):
  260. check_is_fitted(self)
  261. if hasattr(self, 'ebms_'):
  262. feats = self._extract_ebm_features(X)
  263. if hasattr(self, 'scaler_'):
  264. feats = self.scaler_.transform(feats)
  265. if hasattr(self, 'correlation_screener_'):
  266. feats = self.correlation_screener_.transform(feats)
  267. return self.lin_model.predict_proba(feats)
  268. # multi-output without multitask learning
  269. elif hasattr(self, 'ebm_multioutput_'):
  270. return self.ebm_multioutput_.predict_proba(X)
  271. # single-task standard
  272. elif hasattr(self, 'ebm_'):
  273. return self.ebm_.predict_proba(X)
  274. class MultiTaskGAMRegressor(MultiTaskGAM, RegressorMixin):
  275. ...
  276. class MultiTaskGAMClassifier(MultiTaskGAM, ClassifierMixin):
  277. ...
Tip!

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

Comments

Loading...