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

marginal_shrinkage_linear_model.py 13 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
  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 LinearRegression, RidgeCV, Ridge, ElasticNet, ElasticNetCV
  6. from sklearn.tree import DecisionTreeRegressor
  7. from sklearn.utils.multiclass import check_classification_targets
  8. from sklearn.utils.validation import check_X_y, check_array, _check_sample_weight
  9. from sklearn.model_selection import train_test_split
  10. from sklearn.metrics import accuracy_score, roc_auc_score
  11. from tqdm import tqdm
  12. from sklearn.preprocessing import StandardScaler
  13. from collections import defaultdict
  14. import imodels
  15. from sklearn.base import RegressorMixin, ClassifierMixin
  16. class MarginalShrinkageLinearModel(BaseEstimator):
  17. """Linear model that shrinks towards the marginal effects of each feature."""
  18. def __str__(self):
  19. return (
  20. repr(self)
  21. .replace("MarginalShrinkageLinearModel", "MSLM")
  22. .replace("Regressor", "Reg")
  23. .replace("Classifier", "Clf")
  24. )
  25. def __init__(
  26. self,
  27. est_marginal_name="ridge",
  28. est_main_name="ridge",
  29. marginal_divide_by_d=True,
  30. marginal_sign_constraint=False,
  31. alphas=np.logspace(-3, 5, num=9).tolist(),
  32. elasticnet_ratio=0.5,
  33. random_state=None,
  34. ):
  35. """
  36. Params
  37. ------
  38. est_marginal_name : str
  39. Name of estimator to use for marginal effects (marginal regression)
  40. If "None", then assume marginal effects are zero (standard Ridge)
  41. est_main_name : str
  42. Name of estimator to use for main effects
  43. If "None", then assume marginal effects are zero (standard Ridge)
  44. "ridge", "lasso", "elasticnet"
  45. marginal_divide_by_d : bool
  46. If True, then divide marginal effects by n_features
  47. marginal_sign_constraint : bool
  48. If True, then constrain main effects to be same sign as marginal effects
  49. alphas: Tuple[float]
  50. Alphas to try for regularized regression (only main, not marginal)
  51. elasticnet_ratio : float
  52. If using elasticnet, Ratio of l1 to l2 penalty for elastic net
  53. random_state : int
  54. Random seed
  55. """
  56. self.random_state = random_state
  57. self.est_marginal_name = est_marginal_name
  58. self.est_main_name = est_main_name
  59. self.marginal_divide_by_d = marginal_divide_by_d
  60. self.marginal_sign_constraint = marginal_sign_constraint
  61. self.elasticnet_ratio = elasticnet_ratio
  62. if alphas is None:
  63. alphas = np.logspace(-3, 5, num=9).tolist()
  64. elif isinstance(alphas, float) or isinstance(alphas, int):
  65. alphas = [alphas]
  66. self.alphas = alphas
  67. def fit(self, X, y, sample_weight=None):
  68. # checks
  69. X, y = check_X_y(X, y, accept_sparse=False, multi_output=False)
  70. sample_weight = _check_sample_weight(sample_weight, X, dtype=None)
  71. if isinstance(self, ClassifierMixin):
  72. check_classification_targets(y)
  73. self.classes_, y = np.unique(y, return_inverse=True)
  74. # preprocess X and y
  75. self.scalar_X_ = StandardScaler()
  76. X = self.scalar_X_.fit_transform(X)
  77. if isinstance(self, RegressorMixin):
  78. self.scalar_y_ = StandardScaler()
  79. y = self.scalar_y_.fit_transform(y.reshape(-1, 1)).squeeze()
  80. # fit marginal
  81. self.coef_marginal_ = self._fit_marginal(X, y, sample_weight)
  82. # fit main
  83. self.est_main_ = self._fit_main(
  84. X, y, sample_weight, self.coef_marginal_)
  85. return self
  86. def _fit_marginal(self, X, y, sample_weight):
  87. # initialize marginal estimator
  88. ALPHAS_MARGINAL = np.logspace(-1, 3, num=5).tolist()
  89. est_marginal = self._get_est_from_name(
  90. self.est_marginal_name,
  91. alphas=ALPHAS_MARGINAL,
  92. marginal_sign_constraint=False,
  93. )
  94. # fit marginal estimator to each feature
  95. if est_marginal is None:
  96. coef_marginal_ = np.zeros(X.shape[1])
  97. else:
  98. coef_marginal_ = []
  99. for i in range(X.shape[1]):
  100. est_marginal.fit(X[:, i].reshape(-1, 1), y,
  101. sample_weight=sample_weight)
  102. coef_marginal_.append(deepcopy(est_marginal.coef_))
  103. coef_marginal_ = np.vstack(coef_marginal_).squeeze()
  104. # evenly divide effects among features
  105. if self.marginal_divide_by_d:
  106. coef_marginal_ /= X.shape[1]
  107. return coef_marginal_
  108. def _fit_main(self, X, y, sample_weight, coef_marginal_):
  109. # constrain main effects to be same sign as marginal effects by flipping sign
  110. # of X appropriately and refitting with a non-negative least squares
  111. est_main_ = self._get_est_from_name(
  112. self.est_main_name,
  113. alphas=self.alphas,
  114. marginal_sign_constraint=self.marginal_sign_constraint,
  115. )
  116. if self.marginal_sign_constraint:
  117. assert self.est_marginal_name is not None, "must have marginal effects"
  118. coef_signs = np.sign(coef_marginal_)
  119. X = X * coef_signs
  120. est_main_.fit(X, y, sample_weight=sample_weight)
  121. est_main_.coef_ = est_main_.coef_ * coef_signs
  122. # check that signs do not disagree
  123. coef_final_signs = np.sign(est_main_.coef_)
  124. assert np.all(
  125. (coef_final_signs == coef_signs) | (coef_final_signs == 0)
  126. ), "signs should agree but" + str(np.sign(est_main_.coef_), coef_signs)
  127. elif est_main_ is None:
  128. # fit dummy clf and override coefs
  129. est_main_ = ElasticNetCV(fit_intercept=False)
  130. est_main_.fit(X[:5], y[:5])
  131. est_main_.coef_ = coef_marginal_
  132. else:
  133. # fit main estimator
  134. # predicting residuals is the same as setting a prior over coef_marginal
  135. # because we do solve change of variables ridge(prior = coef = coef - coef_marginal)
  136. preds_marginal = X @ coef_marginal_
  137. residuals = y - preds_marginal
  138. est_main_.fit(X, residuals, sample_weight=sample_weight)
  139. est_main_.coef_ = est_main_.coef_ + coef_marginal_
  140. return est_main_
  141. def _get_est_from_name(self, est_name, alphas, marginal_sign_constraint):
  142. L1_RATIOS = {
  143. "ridge": 1e-6,
  144. "lasso": 1,
  145. "elasticnet": self.elasticnet_ratio,
  146. }
  147. if est_name not in L1_RATIOS:
  148. return None
  149. else:
  150. if est_name == "ridge" and not marginal_sign_constraint:
  151. # this implementation is better than ElasticNetCV with l1_ratio close to 0
  152. return RidgeCV(
  153. alphas=alphas,
  154. fit_intercept=False,
  155. )
  156. return ElasticNetCV(
  157. l1_ratio=L1_RATIOS[est_name],
  158. alphas=alphas,
  159. max_iter=10000,
  160. fit_intercept=False,
  161. positive=bool(marginal_sign_constraint),
  162. )
  163. def predict_proba(self, X):
  164. X = self.scalar_X_.transform(X)
  165. return self.est_main_.predict_proba(X)
  166. def predict(self, X):
  167. X = self.scalar_X_.transform(X)
  168. pred = self.est_main_.predict(X)
  169. return self.scalar_y_.inverse_transform(pred.reshape(-1, 1)).squeeze()
  170. class MarginalShrinkageLinearModelRegressor(
  171. MarginalShrinkageLinearModel, RegressorMixin
  172. ):
  173. ...
  174. # class MarginalShrinkageLinearModelClassifier(
  175. # MarginalShrinkageLinearModel, ClassifierMixin
  176. # ):
  177. # ...
  178. class MarginalLinearModel(BaseEstimator):
  179. """Linear model that only fits marginal effects of each feature.
  180. """
  181. def __init__(self, alpha=1.0, l1_ratio=0.5, max_iter=1000, random_state=None):
  182. '''Arguments are passed to sklearn.linear_model.ElasticNet
  183. '''
  184. self.alpha = alpha
  185. self.l1_ratio = l1_ratio
  186. self.max_iter = max_iter
  187. self.random_state = random_state
  188. def fit(self, X, y, sample_weight=None):
  189. # checks
  190. X, y = check_X_y(X, y, accept_sparse=False, multi_output=False)
  191. sample_weight = _check_sample_weight(sample_weight, X, dtype=None)
  192. if isinstance(self, ClassifierMixin):
  193. check_classification_targets(y)
  194. self.classes_, y = np.unique(y, return_inverse=True)
  195. # fit marginal estimator to each feature
  196. coef_marginal_ = []
  197. for i in range(X.shape[1]):
  198. est_marginal = ElasticNet(alpha=self.alpha, l1_ratio=self.l1_ratio,
  199. max_iter=self.max_iter, random_state=self.random_state)
  200. est_marginal.fit(X[:, i].reshape(-1, 1), y,
  201. sample_weight=sample_weight)
  202. coef_marginal_.append(deepcopy(est_marginal.coef_))
  203. coef_marginal_ = np.vstack(coef_marginal_).squeeze()
  204. self.coef_ = coef_marginal_ / X.shape[1]
  205. self.alpha_ = self.alpha
  206. return self
  207. def predict_proba(self, X):
  208. X = check_array(X, accept_sparse=False, dtype=None)
  209. return X @ self.coef_
  210. def predict(self, X):
  211. probs = self.predict_proba(X)
  212. if isinstance(self, ClassifierMixin):
  213. return np.argmax(probs, axis=1)
  214. else:
  215. return probs
  216. class MarginalLinearRegressor(MarginalLinearModel, RegressorMixin):
  217. ...
  218. class MarginalLinearClassifier(MarginalLinearModel, ClassifierMixin):
  219. ...
  220. # if __name__ == '__main__':
  221. # X, y = imodels.get_clean_dataset('heart')
  222. # X_train, X_test, y_train, y_test = train_test_split(
  223. # X, y, random_state=42, test_size=0.2)
  224. # m = MarginalLinearModelRegressor()
  225. # m.fit(X_train, y_train)
  226. # print(m.coef_)
  227. # print(m.predict(X_test))
  228. # print(m.score(X_test, y_test))
  229. if __name__ == "__main__":
  230. # X, y, feature_names = imodels.get_clean_dataset("heart")
  231. X, y, feature_names = imodels.get_clean_dataset(
  232. **imodels.util.data_util.DSET_KWARGS["california_housing"]
  233. )
  234. # scale the data
  235. X = StandardScaler().fit_transform(X)
  236. y = StandardScaler().fit_transform(y.reshape(-1, 1)).squeeze()
  237. print("shapes", X.shape, y.shape, "nunique", np.unique(y).size)
  238. X_train, X_test, y_train, y_test = train_test_split(
  239. X, y, random_state=42, test_size=0.2
  240. )
  241. coefs = []
  242. alphas = (0.1, 1, 10, 100, 1000, 10000) # (0.1, 1, 10, 100, 1000, 10000)
  243. # alphas = 10000
  244. kwargs = dict(
  245. random_state=42,
  246. alphas=alphas,
  247. )
  248. results = defaultdict(list)
  249. for m in [
  250. # MarginalShrinkageLinearModelRegressor(**kwargs),
  251. # MarginalShrinkageLinearModelRegressor(
  252. # est_marginal_name=None, **kwargs),
  253. # MarginalShrinkageLinearModelRegressor(
  254. # est_main_name=None,
  255. # **kwargs,
  256. # ),
  257. # MarginalShrinkageLinearModelRegressor(
  258. # est_marginal_name="ridge",
  259. # est_main_name="ridge",
  260. # marginal_sign_constraint=True,
  261. # **kwargs,
  262. # ),
  263. # MarginalShrinkageLinearModelRegressor(
  264. # est_marginal_name=None, est_main_name="lasso", **kwargs
  265. # ),
  266. # MarginalShrinkageLinearModelRegressor(
  267. # est_marginal_name="ridge",
  268. # est_main_name="lasso",
  269. # marginal_sign_constraint=True,
  270. # **kwargs,
  271. # ),
  272. MarginalLinearRegressor(alpha=1.0),
  273. RidgeCV(alphas=alphas, fit_intercept=False),
  274. ]:
  275. results["model_name"].append(str(m))
  276. m.fit(X_train, y_train)
  277. # check roc auc score
  278. if isinstance(m, ClassifierMixin):
  279. results["train_roc"].append(
  280. roc_auc_score(y_train, m.predict_proba(X_train)[:, 1])
  281. )
  282. results["test_roc"].append(
  283. roc_auc_score(y_test, m.predict_proba(X_test)[:, 1])
  284. )
  285. results["acc_train"].append(
  286. accuracy_score(y_train, m.predict(X_train)))
  287. results["acc_test"].append(
  288. accuracy_score(y_test, m.predict(X_test)))
  289. else:
  290. y_pred = m.predict(X_test)
  291. results["train_mse"].append(
  292. np.mean((y_train - m.predict(X_train)) ** 2))
  293. results["test_mse"].append(np.mean((y_test - y_pred) ** 2))
  294. results["train_r2"].append(m.score(X_train, y_train))
  295. results["test_r2"].append(m.score(X_test, y_test))
  296. if isinstance(m, MarginalShrinkageLinearModelRegressor):
  297. lin = m.est_main_
  298. else:
  299. lin = m
  300. coefs.append(deepcopy(lin.coef_))
  301. print("alpha best", lin.alpha_)
  302. # diffs = pd.DataFrame({str(i): coefs[i] for i in range(len(coefs))})
  303. # diffs["diff 0 - 1"] = diffs["0"] - diffs["1"]
  304. # diffs["diff 1 - 2"] = diffs["1"] - diffs["2"]
  305. # print(diffs)
  306. # don't round strings
  307. with pd.option_context(
  308. "display.max_rows", None, "display.max_columns", None, "display.width", 1000
  309. ):
  310. print(pd.DataFrame(results).round(3))
Tip!

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

Comments

Loading...