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

ppms.py 22 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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
  1. import copy
  2. from abc import ABC, abstractmethod
  3. import warnings
  4. from functools import partial
  5. import numpy as np
  6. import scipy as sp
  7. from sklearn.linear_model import RidgeCV, Ridge, \
  8. LogisticRegression, HuberRegressor, Lasso
  9. from sklearn.metrics import log_loss, mean_squared_error
  10. from scipy.special import softmax
  11. class PartialPredictionModelBase(ABC):
  12. """
  13. An interface for partial prediction models, objects that make use of a
  14. block partitioned data object, fits a regression or classification model
  15. on all the data, and for each block k, applies the model on a modified copy
  16. of the data (by either imputing the mean of each feature in block k or
  17. imputing the mean of each feature not in block k.)
  18. Parameters
  19. ----------
  20. estimator: scikit estimator object
  21. The regression or classification model used to obtain predictions.
  22. """
  23. def __init__(self, estimator):
  24. self.estimator = copy.deepcopy(estimator)
  25. self.is_fitted = False
  26. def fit(self, X, y):
  27. """
  28. Fit the partial prediction model.
  29. Parameters
  30. ----------
  31. X: ndarray of shape (n_samples, n_features)
  32. The covariate matrix.
  33. y: ndarray of shape (n_samples, n_targets)
  34. The observed responses.
  35. """
  36. self._fit_model(X, y)
  37. self.is_fitted = True
  38. @abstractmethod
  39. def _fit_model(self, X, y):
  40. """
  41. Fit the regression or classification model on all the data.
  42. Parameters
  43. ----------
  44. X: ndarray of shape (n_samples, n_features)
  45. The covariate matrix.
  46. y: ndarray of shape (n_samples, n_targets)
  47. The observed responses.
  48. """
  49. pass
  50. @abstractmethod
  51. def predict(self, X):
  52. """
  53. Make predictions on new data using the fitted model.
  54. Parameters
  55. ----------
  56. X: ndarray of shape (n_samples, n_features)
  57. The covariate matrix, for which to make predictions.
  58. """
  59. pass
  60. @abstractmethod
  61. def predict_full(self, blocked_data):
  62. """
  63. Make predictions using all the data based upon the fitted model.
  64. Used to make full predictions in MDI+.
  65. Parameters
  66. ----------
  67. blocked_data: BlockPartitionedData object
  68. The block partitioned covariate data, for which to make predictions.
  69. """
  70. pass
  71. @abstractmethod
  72. def predict_partial_k(self, blocked_data, k, mode):
  73. """
  74. Make predictions on modified copies of the data based on the fitted model,
  75. for a particular feature k of interest. Used to get partial predictions
  76. for feature k in MDI+.
  77. Parameters
  78. ----------
  79. blocked_data: BlockPartitionedData object
  80. The block partitioned covariate data, for which to make predictions.
  81. k: int
  82. Index of feature in X of interest.
  83. mode: string in {"keep_k", "keep_rest"}
  84. Mode for the method. "keep_k" imputes the mean of each feature not
  85. in block k, "keep_rest" imputes the mean of each feature in block k
  86. """
  87. pass
  88. def predict_partial(self, blocked_data, mode):
  89. """
  90. Make predictions on modified copies of the data based on the fitted model,
  91. for each feature under study. Used to get partial predictions in MDI+.
  92. Parameters
  93. ----------
  94. blocked_data: BlockPartitionedData object
  95. The block partitioned covariate data, for which to make predictions.
  96. mode: string in {"keep_k", "keep_rest"}
  97. Mode for the method. "keep_k" imputes the mean of each feature not
  98. in block k, "keep_rest" imputes the mean of each feature in block k
  99. Returns
  100. -------
  101. List of length n_features of partial predictions for each feature.
  102. """
  103. n_blocks = blocked_data.n_blocks
  104. partial_preds = {}
  105. for k in range(n_blocks):
  106. partial_preds[k] = self.predict_partial_k(blocked_data, k, mode)
  107. return partial_preds
  108. class _GenericPPM(PartialPredictionModelBase, ABC):
  109. """
  110. Partial prediction model for arbitrary estimators. May be slow.
  111. """
  112. def __init__(self, estimator):
  113. super().__init__(estimator)
  114. def _fit_model(self, X, y):
  115. self.estimator.fit(X, y)
  116. def predict(self, X):
  117. return self.estimator.predict(X)
  118. def predict_full(self, blocked_data):
  119. return self.predict(blocked_data.get_all_data())
  120. def predict_partial_k(self, blocked_data, k, mode):
  121. modified_data = blocked_data.get_modified_data(k, mode)
  122. return self.predict(modified_data)
  123. class GenericRegressorPPM(_GenericPPM, PartialPredictionModelBase, ABC):
  124. """
  125. Partial prediction model for arbitrary regression estimators. May be slow.
  126. """
  127. ...
  128. class GenericClassifierPPM(_GenericPPM, PartialPredictionModelBase, ABC):
  129. """
  130. Partial prediction model for arbitrary classification estimators. May be slow.
  131. """
  132. def predict_proba(self, X):
  133. return self.estimator.predict_proba(X)
  134. def predict_partial_k(self, blocked_data, k, mode):
  135. modified_data = blocked_data.get_modified_data(k, mode)
  136. return self.predict_proba(modified_data)
  137. class _GlmPPM(PartialPredictionModelBase, ABC):
  138. """
  139. PPM class for GLM estimator. The GLM estimator is assumed to have a single
  140. regularization hyperparameter accessible as a named attribute called either
  141. "alpha" or "C". When fitting, the PPM class will select this hyperparameter
  142. using efficient approximate leave-one-out calculations.
  143. Parameters
  144. ----------
  145. estimator: scikit estimator object
  146. The regression or classification model used to obtain predictions.
  147. loo: bool
  148. Flag for whether to also use LOO calculations for making predictions.
  149. alpha_grid: ndarray of shape (n_alphas, )
  150. The grid of alpha values for hyperparameter optimization.
  151. inv_link_fn: function
  152. The inverse of the GLM link function.
  153. l_dot: function
  154. The first derivative of the log likelihood (with respect to the linear
  155. predictor), as a function of the linear predictor and the response y.
  156. l_doubledot: function
  157. The second derivative of the log likelihood (with respect to the linear
  158. predictor), as a function of the linear predictor and the true response
  159. y.
  160. r_doubledot: function
  161. The second derivative of the regularizer with respect to each
  162. coefficient. We assume that the regularizer is separable and symmetric
  163. with respect to the coefficients.
  164. hyperparameter_scorer: function
  165. The function used to evaluate different hyperparameter values.
  166. Typically, this is the loglikelihood as a function of the linear
  167. predictor and the true response y.
  168. trim: float
  169. The amount by which to trim predicted probabilities away from 0 and 1.
  170. This helps to stabilize some loss calculations.
  171. gcv_mode: string in {"auto", "svd", "eigen"}
  172. Flag indicating which strategy to use when performing leave-one-out
  173. cross-validation for ridge regression, if applicable.
  174. See gcv_mode in sklearn.linear_model.RidgeCV for details.
  175. """
  176. def __init__(self, estimator, loo=True, alpha_grid=np.logspace(-4, 4, 10),
  177. inv_link_fn=lambda a: a, l_dot=lambda a, b: b - a,
  178. l_doubledot=lambda a, b: 1, r_doubledot=lambda a: 1,
  179. hyperparameter_scorer=mean_squared_error,
  180. trim=None, gcv_mode='auto'):
  181. super().__init__(estimator)
  182. self.loo = loo
  183. self.alpha_grid = alpha_grid
  184. self.inv_link_fn = inv_link_fn
  185. self.l_dot = l_dot
  186. self.l_doubledot = l_doubledot
  187. self.r_doubledot = r_doubledot
  188. self.trim = trim
  189. self.gcv_mode = gcv_mode
  190. self.hyperparameter_scorer = hyperparameter_scorer
  191. self.alpha_ = {}
  192. self.loo_coefficients_ = {}
  193. self.coefficients_ = {}
  194. self._intercept_pred = None
  195. def _fit_model(self, X, y):
  196. y_train = copy.deepcopy(y)
  197. if y_train.ndim == 1:
  198. y_train = y_train.reshape(-1, 1)
  199. self._n_outputs = y_train.shape[1]
  200. for j in range(self._n_outputs):
  201. yj = y_train[:, j]
  202. # Compute regularization hyperparameter using approximate LOOCV
  203. if isinstance(self.estimator, Ridge):
  204. cv = RidgeCV(alphas=self.alpha_grid, gcv_mode=self.gcv_mode)
  205. cv.fit(X, yj)
  206. self.alpha_[j] = cv.alpha_
  207. else:
  208. self.alpha_[j] = self._get_aloocv_alpha(X, yj)
  209. # Fit the model on the training set and compute the coefficients
  210. if self.loo:
  211. self.loo_coefficients_[j] = \
  212. self._fit_loo_coefficients(X, yj, self.alpha_[j])
  213. self.coefficients_[j] = _extract_coef_and_intercept(self.estimator)
  214. else:
  215. self.coefficients_[j] = \
  216. self._fit_coefficients(X, yj, self.alpha_[j])
  217. def predict(self, X):
  218. preds_list = []
  219. for j in range(self._n_outputs):
  220. preds_j = _get_preds(X, self.coefficients_[j], self.inv_link_fn)
  221. preds_list.append(preds_j)
  222. if self._n_outputs == 1:
  223. preds = preds_list[0]
  224. else:
  225. preds = np.stack(preds_list, axis=1)
  226. return _trim_values(preds, self.trim)
  227. def predict_loo(self, X):
  228. preds_list = []
  229. for j in range(self._n_outputs):
  230. if self.loo:
  231. preds_j = _get_preds(X, self.loo_coefficients_[j], self.inv_link_fn)
  232. else:
  233. preds_j = _get_preds(X, self.coefficients_[j], self.inv_link_fn)
  234. preds_list.append(preds_j)
  235. if self._n_outputs == 1:
  236. preds = preds_list[0]
  237. else:
  238. preds = np.stack(preds_list, axis=1)
  239. return _trim_values(preds, self.trim)
  240. def predict_full(self, blocked_data):
  241. return self.predict_loo(blocked_data.get_all_data())
  242. def predict_partial_k(self, blocked_data, k, mode):
  243. assert mode in ["keep_k", "keep_rest"]
  244. if mode == "keep_k":
  245. block_indices = blocked_data.get_block_indices(k)
  246. data_block = blocked_data.get_block(k)
  247. elif mode == "keep_rest":
  248. block_indices = blocked_data.get_all_except_block_indices(k)
  249. data_block = blocked_data.get_all_except_block(k)
  250. if len(block_indices) == 0: # If empty block
  251. return self.intercept_pred
  252. else:
  253. partial_preds_list = []
  254. for j in range(self._n_outputs):
  255. if self.loo:
  256. coefs = self.loo_coefficients_[j][:, block_indices]
  257. intercept = self.loo_coefficients_[j][:, -1]
  258. else:
  259. coefs = self.coefficients_[j][block_indices]
  260. intercept = self.coefficients_[j][-1]
  261. partial_preds_j = _get_preds(
  262. data_block, coefs, self.inv_link_fn, intercept
  263. )
  264. partial_preds_list.append(partial_preds_j)
  265. if self._n_outputs == 1:
  266. partial_preds = partial_preds_list[0]
  267. else:
  268. partial_preds = np.stack(partial_preds_list, axis=1)
  269. return _trim_values(partial_preds, self.trim)
  270. @property
  271. def intercept_pred(self):
  272. if self._intercept_pred is None:
  273. self._intercept_pred = np.array([
  274. _trim_values(self.inv_link_fn(self.coefficients_[j][-1]), self.trim) \
  275. for j in range(self._n_outputs)
  276. ])
  277. return ("constant_model", self._intercept_pred)
  278. def _fit_coefficients(self, X, y, alpha):
  279. _set_alpha(self.estimator, alpha)
  280. self.estimator.fit(X, y)
  281. return _extract_coef_and_intercept(self.estimator)
  282. def _fit_loo_coefficients(self, X, y, alpha, max_h=1-1e-4):
  283. """
  284. Get the coefficient (and intercept) for each LOO model. Since we fit
  285. one model for each sample, this gives an ndarray of shape (n_samples,
  286. n_features + 1)
  287. """
  288. orig_coef_ = self._fit_coefficients(X, y, alpha)
  289. X1 = np.hstack([X, np.ones((X.shape[0], 1))])
  290. orig_preds = _get_preds(X, orig_coef_, self.inv_link_fn)
  291. support_idxs = orig_coef_ != 0
  292. if not any(support_idxs):
  293. return orig_coef_ * np.ones_like(X1)
  294. X1 = X1[:, support_idxs]
  295. orig_coef_ = orig_coef_[support_idxs]
  296. l_doubledot_vals = self.l_doubledot(y, orig_preds)
  297. J = X1.T * l_doubledot_vals @ X1
  298. if self.r_doubledot is not None:
  299. r_doubledot_vals = self.r_doubledot(orig_coef_) * \
  300. np.ones_like(orig_coef_)
  301. r_doubledot_vals[-1] = 0 # Do not penalize constant term
  302. reg_curvature = np.diag(r_doubledot_vals)
  303. J += alpha * reg_curvature
  304. normal_eqn_mat = np.linalg.inv(J) @ X1.T
  305. h_vals = np.sum(X1.T * normal_eqn_mat, axis=0) * l_doubledot_vals
  306. h_vals[h_vals == 1] = max_h
  307. loo_coef_ = orig_coef_[:, np.newaxis] + \
  308. normal_eqn_mat * self.l_dot(y, orig_preds) / (1 - h_vals)
  309. if not all(support_idxs):
  310. loo_coef_dense_ = np.zeros((X.shape[1] + 1, X.shape[0]))
  311. loo_coef_dense_[support_idxs, :] = loo_coef_
  312. loo_coef_ = loo_coef_dense_
  313. return loo_coef_.T
  314. def _get_aloocv_alpha(self, X, y):
  315. cv_scores = np.zeros_like(self.alpha_grid)
  316. for i, alpha in enumerate(self.alpha_grid):
  317. loo_coef_ = self._fit_loo_coefficients(X, y, alpha)
  318. X1 = np.hstack([X, np.ones((X.shape[0], 1))])
  319. sample_scores = np.sum(loo_coef_ * X1, axis=1)
  320. preds = _trim_values(self.inv_link_fn(sample_scores), self.trim)
  321. cv_scores[i] = self.hyperparameter_scorer(y, preds)
  322. return self.alpha_grid[np.argmin(cv_scores)]
  323. class GlmRegressorPPM(_GlmPPM, PartialPredictionModelBase, ABC):
  324. """
  325. PPM class for GLM regression estimator.
  326. """
  327. ...
  328. class GlmClassifierPPM(_GlmPPM, PartialPredictionModelBase, ABC):
  329. """
  330. PPM class for GLM classification estimator.
  331. """
  332. def predict_proba(self, X):
  333. probs = self.predict(X)
  334. if probs.ndim == 1:
  335. probs = np.stack([1 - probs, probs], axis=1)
  336. return probs
  337. def predict_proba_loo(self, X):
  338. probs = self.predict_loo(X)
  339. if probs.ndim == 1:
  340. probs = np.stack([1 - probs, probs], axis=1)
  341. return probs
  342. class _RidgePPM(_GlmPPM, PartialPredictionModelBase, ABC):
  343. """
  344. PPM class that uses ridge as the estimator.
  345. Parameters
  346. ----------
  347. loo: bool
  348. Flag for whether to also use LOO calculations for making predictions.
  349. alpha_grid: ndarray of shape (n_alphas, )
  350. The grid of alpha values for hyperparameter optimization.
  351. gcv_mode: string in {"auto", "svd", "eigen"}
  352. Flag indicating which strategy to use when performing leave-one-out
  353. cross-validation for ridge regression.
  354. See gcv_mode in sklearn.linear_model.RidgeCV for details.
  355. **kwargs
  356. Other Parameters are passed on to Ridge().
  357. """
  358. def __init__(self, loo=True, alpha_grid=np.logspace(-5, 5, 100),
  359. gcv_mode='auto', **kwargs):
  360. super().__init__(Ridge(**kwargs), loo, alpha_grid, gcv_mode=gcv_mode)
  361. def set_alphas(self, alphas="default", blocked_data=None, y=None):
  362. full_data = blocked_data.get_all_data()
  363. if alphas == "default":
  364. alphas = get_alpha_grid(full_data, y)
  365. else:
  366. alphas = alphas
  367. self.alpha_grid = alphas
  368. class RidgeRegressorPPM(_RidgePPM, GlmRegressorPPM,
  369. PartialPredictionModelBase, ABC):
  370. """
  371. PPM class for regression that uses ridge as the GLM estimator.
  372. """
  373. ...
  374. class RidgeClassifierPPM(_RidgePPM, GlmClassifierPPM,
  375. PartialPredictionModelBase, ABC):
  376. """
  377. PPM class for classification that uses ridge as the GLM estimator.
  378. """
  379. def predict_proba(self, X):
  380. probs = softmax(self.predict(X))
  381. if probs.ndim == 1:
  382. probs = np.stack([1 - probs, probs], axis=1)
  383. return probs
  384. def predict_proba_loo(self, X):
  385. probs = softmax(self.predict_loo(X))
  386. if probs.ndim == 1:
  387. probs = np.stack([1 - probs, probs], axis=1)
  388. return probs
  389. class LogisticClassifierPPM(GlmClassifierPPM, PartialPredictionModelBase, ABC):
  390. """
  391. PPM class for classification that uses logistic regression as the estimator.
  392. Parameters
  393. ----------
  394. loo: bool
  395. Flag for whether to also use LOO calculations for making predictions.
  396. alpha_grid: ndarray of shape (n_alphas, )
  397. The grid of alpha values for hyperparameter optimization.
  398. max_iter: int
  399. The maximum number of iterations for the LogisticRegression solver.
  400. trim: float
  401. The amount by which to trim predicted probabilities away from 0 and 1.
  402. This helps to stabilize some loss calculations.
  403. **kwargs
  404. Other Parameters are passed on to LogisticRegression().
  405. """
  406. def __init__(self, loo=True, alpha_grid=np.logspace(-2, 3, 25),
  407. penalty='l2', max_iter=1000, trim=0.01, **kwargs):
  408. assert penalty in ['l2', 'l1']
  409. if penalty == 'l2':
  410. r_doubledot = lambda a: 1
  411. elif penalty == 'l1':
  412. r_doubledot = None
  413. super().__init__(LogisticRegression(penalty=penalty, max_iter=max_iter, **kwargs),
  414. loo, alpha_grid,
  415. inv_link_fn=sp.special.expit,
  416. l_doubledot=lambda a, b: b * (1 - b),
  417. r_doubledot=r_doubledot,
  418. hyperparameter_scorer=log_loss,
  419. trim=trim)
  420. class RobustRegressorPPM(GlmRegressorPPM, PartialPredictionModelBase, ABC):
  421. """
  422. PPM class for regression that uses Huber robust regression as the estimator.
  423. Parameters
  424. ----------
  425. loo: bool
  426. Flag for whether to also use LOO calculations for making predictions.
  427. alpha_grid: ndarray of shape (n_alphas, )
  428. The grid of alpha values for hyperparameter optimization.
  429. epsilon: float
  430. The robustness parameter for Huber regression. The smaller the epsilon,
  431. the more robust it is to outliers. Epsilon must be in the range
  432. [1, inf).
  433. **kwargs
  434. Other Parameters are passed on to LogisticRegression().
  435. """
  436. def __init__(self, loo=True, alpha_grid=np.logspace(-2, 3, 25),
  437. epsilon=1.35, max_iter=2000, **kwargs):
  438. loss_fn = partial(huber_loss, epsilon=epsilon)
  439. l_dot = lambda a, b: (b - a) / (1 + ((a - b) / epsilon) ** 2) ** 0.5
  440. l_doubledot=lambda a, b: (1 + (((a - b) / epsilon) ** 2)) ** (-1.5)
  441. super().__init__(
  442. HuberRegressor(max_iter=max_iter, **kwargs), loo, alpha_grid,
  443. l_dot=l_dot,
  444. l_doubledot=l_doubledot,
  445. hyperparameter_scorer=loss_fn)
  446. class LassoRegressorPPM(GlmRegressorPPM, PartialPredictionModelBase, ABC):
  447. """
  448. PPM class for regression that uses lasso as the estimator.
  449. Parameters
  450. ----------
  451. loo: bool
  452. Flag for whether to also use LOO calculations for making predictions.
  453. alpha_grid: ndarray of shape (n_alphas, )
  454. The grid of alpha values for hyperparameter optimization.
  455. **kwargs
  456. Other Parameters are passed on to Lasso().
  457. """
  458. def __init__(self, loo=True, alpha_grid=np.logspace(-2, 3, 25), **kwargs):
  459. super().__init__(Lasso(**kwargs), loo, alpha_grid, r_doubledot=None)
  460. def _trim_values(values, trim=None):
  461. if trim is not None:
  462. assert 0 < trim < 0.5, "Limit must be between 0 and 0.5"
  463. return np.clip(values, trim, 1 - trim)
  464. else:
  465. return values
  466. def _extract_coef_and_intercept(estimator):
  467. """
  468. Get the coefficient vector and intercept from a GLM estimator
  469. """
  470. coef_ = estimator.coef_
  471. intercept_ = estimator.intercept_
  472. if coef_.ndim > 1: # For classifer estimators
  473. coef_ = coef_.ravel()
  474. intercept_ = intercept_[0]
  475. augmented_coef_ = np.append(coef_, intercept_)
  476. return augmented_coef_
  477. def _set_alpha(estimator, alpha):
  478. if hasattr(estimator, "alpha"):
  479. estimator.set_params(alpha=alpha)
  480. elif hasattr(estimator, "C"):
  481. estimator.set_params(C=1/alpha)
  482. else:
  483. warnings.warn("Estimator has no regularization parameter.")
  484. def _get_preds(data_block, coefs, inv_link_fn, intercept=None):
  485. if coefs.ndim > 1: # LOO predictions
  486. if coefs.shape[1] == (data_block.shape[1] + 1):
  487. intercept = coefs[:, -1]
  488. coefs = coefs[:, :-1]
  489. lin_preds = np.sum(data_block * coefs, axis=1) + intercept
  490. else:
  491. if len(coefs) == (data_block.shape[1] + 1):
  492. intercept = coefs[-1]
  493. coefs = coefs[:-1]
  494. lin_preds = data_block @ coefs + intercept
  495. return inv_link_fn(lin_preds)
  496. def huber_loss(y, preds, epsilon=1.35):
  497. """
  498. Evaluates Huber loss function.
  499. Parameters
  500. ----------
  501. y: array-like of shape (n,)
  502. Vector of observed responses.
  503. preds: array-like of shape (n,)
  504. Vector of estimated/predicted responses.
  505. epsilon: float
  506. Threshold, determining transition between squared
  507. and absolute loss in Huber loss function.
  508. Returns
  509. -------
  510. Scalar value, quantifying the Huber loss. Lower loss
  511. indicates better fit.
  512. """
  513. total_loss = 0
  514. for i in range(len(y)):
  515. sample_absolute_error = np.abs(y[i] - preds[i])
  516. if sample_absolute_error < epsilon:
  517. total_loss += 0.5 * ((y[i] - preds[i]) ** 2)
  518. else:
  519. sample_robust_loss = epsilon * sample_absolute_error - 0.5 * \
  520. epsilon ** 2
  521. total_loss += sample_robust_loss
  522. return total_loss / len(y)
  523. def get_alpha_grid(X, y, start=-5, stop=5, num=100):
  524. X = X - X.mean(axis=0)
  525. y = y - y.mean(axis=0)
  526. sigma_sq_ = np.linalg.norm(y, axis=0) ** 2 / X.shape[0]
  527. X_var_ = np.linalg.norm(X, axis=0) ** 2
  528. alpha_opts_ = (X_var_[:, np.newaxis] / (X.T @ y)) ** 2 * sigma_sq_
  529. base = np.max(alpha_opts_)
  530. alphas = np.logspace(start, stop, num=num) * base
  531. return alphas
Tip!

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

Comments

Loading...