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

explanations.py 33 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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
  1. from dataclasses import *
  2. from functools import cached_property
  3. from pathlib import Path
  4. import matplotlib
  5. import matplotlib.pyplot as plt
  6. import shap
  7. from more_itertools import flatten
  8. from sklearn.base import TransformerMixin
  9. import yspecies
  10. from yspecies.dataset import ExpressionDataset
  11. from yspecies.models import Metrics
  12. from yspecies.partition import ExpressionPartitions
  13. from yspecies.utils import *
  14. from loguru import logger
  15. from yspecies.selection import Fold
  16. from scipy.stats import kendalltau
  17. @dataclass(frozen=True)
  18. class FeatureResults:
  19. '''
  20. Feature results class
  21. '''
  22. selected: pd.DataFrame
  23. folds: List[Fold]
  24. partitions: ExpressionPartitions = field(default_factory=lambda: None)
  25. parameters: Dict = field(default_factory=lambda: None)
  26. nan_as_zero: bool = True
  27. @cached_property
  28. def explanations(self):
  29. return [f.explanation for f in self.folds]
  30. def write(self, folder: Path, name: str, with_folds: bool = True, folds_name: str = None):
  31. folds_name = name if folds_name is None else folds_name
  32. folder.mkdir(exist_ok=True)
  33. self.partitions.write(folder, name)
  34. if with_folds:
  35. self.write_folds(folder, folds_name)
  36. return folder
  37. def write_folds(self, folder: Path, name: str = "fold"):
  38. folder.mkdir(exist_ok=True)
  39. for i, f in enumerate(self.folds):
  40. p = folder / f"{name}_{str(i)}_model.txt"
  41. f.model.save_model(str(p))
  42. self.metrics_df.to_csv(folder / f"{name}_{str(i)}_metrics.tsv", sep="\t")
  43. if self.partitions.has_hold_out:
  44. self.hold_out_metrics.to_csv(folder / f"{name}_{str(i)}_metrics_hold_out.tsv", sep="\t")
  45. return folder
  46. @property
  47. def to_predict(self):
  48. return self.partitions.features.to_predict
  49. @cached_property
  50. def kendall_tau_abs_mean(self):
  51. return self.selected[f"kendall_tau_to_{self.to_predict}"].abs().mean()
  52. @property
  53. def head(self):
  54. return self.folds[0]
  55. @cached_property
  56. def validation_species(self):
  57. return [f.validation_species for f in self.folds]
  58. @property
  59. def metrics_average(self) -> Metrics:
  60. return yspecies.selection.Metrics.average([f.metrics for f in self.folds])
  61. @property
  62. def validation_metrics_average(self):
  63. lst = [f.validation_metrics for f in self.folds if f.validation_metrics is not None]
  64. return None if len(lst) == 0 else yspecies.selection.Metrics.average(lst)
  65. @cached_property
  66. def validation_metrics(self):
  67. lst = [f.validation_metrics for f in self.folds if f.validation_metrics is not None]
  68. return None if len(lst) == 0 else yspecies.selection.Metrics.to_dataframe(lst)
  69. @cached_property
  70. def metrics(self) -> Metrics:
  71. return yspecies.selection.Metrics.to_dataframe([f.metrics for f in self.folds])
  72. @cached_property
  73. def metrics_df(self) -> pd.DataFrame:
  74. return self.metrics.join(pd.Series(data=self.validation_species, name="validation_species"))
  75. @cached_property
  76. def hold_out_metrics(self) -> pd.DataFrame:
  77. return yspecies.selection.Metrics.to_dataframe([f.validation_metrics for f in self.folds])\
  78. .join(pd.Series(data =self.partitions.hold_out_species * self.partitions.n_cv_folds, name="hold_out_species"))
  79. def __repr__(self):
  80. #to fix jupyter freeze (see https://github.com/ipython/ipython/issues/9771 )
  81. return self._repr_html_()
  82. @cached_property
  83. def shap_sums(self):
  84. #TODO: rewrite
  85. shap_positive_sums = pd.DataFrame(np.vstack([np.sum(more_or_value(v, 0.0, 0.0), axis=0) for v in self.shap_values]).T, index=self.partitions.X_T.index)
  86. shap_positive_sums = shap_positive_sums.rename(columns={c:f"plus_shap_{c}" for c in shap_positive_sums.columns})
  87. shap_negative_sums = pd.DataFrame(np.vstack([np.sum(less_or_value(v, 0.0, 0.0), axis=0) for v in self.shap_values]).T, index=self.partitions.X_T.index)
  88. shap_negative_sums = shap_negative_sums.rename(columns={c:f"minus_shap_{c}" for c in shap_negative_sums.columns})
  89. sh_cols = [c for c in flatten(zip(shap_positive_sums, shap_negative_sums))]
  90. shap_sums = shap_positive_sums.join(shap_negative_sums)[sh_cols]
  91. return shap_sums
  92. @cached_property
  93. def stable_shap_dataframe(self) -> pd.DataFrame:
  94. return pd.DataFrame(data=self.stable_shap_values, index=self.head.shap_dataframe.index, columns=self.head.shap_dataframe.columns)
  95. @cached_property
  96. def stable_shap_dataframe_T(self) ->pd.DataFrame:
  97. transposed = self.stable_shap_dataframe.T
  98. transposed.index.name = "ensembl_id"
  99. return transposed
  100. def gene_details(self, symbol: str, samples: pd.DataFrame):
  101. '''
  102. Returns details of the genes (which shap values per each sample)
  103. :param symbol:
  104. :param samples:
  105. :return:
  106. '''
  107. shaped = self.selected_extended[self.selected_extended["symbol"] == symbol]
  108. id = shaped.index[0]
  109. print(f"general info: {shaped.iloc[0][0:3]}")
  110. shaped.index = ["shap_values"]
  111. exp = self.partitions.X_T.loc[self.partitions.X_T.index == id]
  112. exp.index = ["expressions"]
  113. joined = pd.concat([exp, shaped], axis=0)
  114. result = joined.T.join(samples)
  115. result.index.name = "run"
  116. return result
  117. @cached_property
  118. def selected_extended(self):
  119. return self.selected.join(self.stable_shap_dataframe_T, how="left")
  120. @cached_property
  121. def mean_shap_values(self) -> np.ndarray:
  122. return np.mean(np.nan_to_num(self.stable_shap_values, 0.0), axis=0) if self.nan_as_zero else np.nanmean(self.stable_shap_values, axis=0)
  123. @cached_property
  124. def stable_shap_values(self) -> np.ndarray:
  125. return np.mean(np.nan_to_num(self.shap_values, 0.0), axis=0) if self.nan_as_zero else np.nanmean(self.shap_values, axis=0)
  126. @cached_property
  127. def stable_interaction_values(self):
  128. return np.mean(np.nan_to_num(self.interaction_values, 0.0), axis=0) if self.nan_as_zero else np.nanmean(self.interaction_values, axis=0)
  129. @cached_property
  130. def shap_dataframes(self) -> List[np.ndarray]:
  131. return [f.shap_dataframe for f in self.folds]
  132. @cached_property
  133. def shap_values(self) -> List[np.ndarray]:
  134. return [f.shap_values for f in self.folds]
  135. @cached_property
  136. def interaction_values(self) -> List[np.ndarray]:
  137. return [f.interaction_values for f in self.folds]
  138. @cached_property
  139. def feature_names(self) -> np.ndarray:
  140. gene_names = self.partitions.data.genes_meta["symbol"].values
  141. return np.concatenate([self.partitions.features.species_non_categorical, gene_names, [c+"_encoded" for c in self.partitions.features.categorical]])
  142. @cached_property
  143. def expected_values_mean(self):
  144. return np.mean([f.expected_value for f in self.folds])
  145. @cached_property
  146. def expected_values(self):
  147. return [f.expected_value for f in self.folds]
  148. def make_figure(self, save: Path, figsize: Tuple[float, float] = None) -> matplotlib.figure.Figure:
  149. fig: matplotlib.figure.Figure = plt.gcf()
  150. if figsize is not None:
  151. #print(f"changing figsize to {str(figsize)}")
  152. plt.rcParams["figure.figsize"] = figsize
  153. fig.set_size_inches(figsize[0], figsize[1], forward=True)
  154. if save is not None:
  155. from IPython.display import set_matplotlib_formats
  156. set_matplotlib_formats('svg')
  157. plt.savefig(save)
  158. plt.close()
  159. return fig
  160. def _plot_(self, shap_values: List[np.ndarray] or np.ndarray, gene_names: bool = True, save: Path = None,
  161. max_display=None, title=None, layered_violin_max_num_bins = 20,
  162. plot_type=None, color=None, axis_color="#333333", alpha=1, class_names=None, plot_size = "auto", custom_data_frame: pd.DataFrame = None
  163. ):
  164. df = self.partitions.X if custom_data_frame is None else custom_data_frame
  165. #shap.summary_plot(shap_values, self.partitions.X, show=False)
  166. feature_names = None if gene_names is False else self.feature_names
  167. shap.summary_plot(shap_values, df, feature_names=feature_names, show=False,
  168. max_display=max_display, title=title, layered_violin_max_num_bins=layered_violin_max_num_bins,
  169. class_names=class_names,
  170. # class_inds=class_inds,
  171. plot_type=plot_type,
  172. color=color, axis_color=axis_color, alpha=alpha, plot_size = plot_size
  173. )
  174. return self.make_figure(save)
  175. @cached_property
  176. def explanation_mean(self) -> shap.Explanation:
  177. exp = sum(self.explanations) / len(self.explanations)
  178. exp.feature_names = self.feature_names
  179. return exp
  180. def filter_explanation(self, filter: Callable[[pd.DataFrame], pd.DataFrame]) -> shap.Explanation:
  181. exp: shap.Explanation = self.mean_shap_values.copy()
  182. exp.values = self.filter_shap(filter)
  183. return exp
  184. def filter_shap(self, filter: Callable[[pd.DataFrame], pd.DataFrame]) -> np.ndarray:
  185. #print("VERY UNSAFE FUNCTION!")
  186. x = self.partitions.X
  187. x_t = self.partitions.X_T
  188. upd_samples = filter(x)
  189. row_df = x[[]].copy()
  190. row_df["ind"] = np.arange(len(row_df))
  191. row_indexes = row_df.join(upd_samples[[]], how = "inner").ind.to_list()
  192. col_df = x_t[[]]
  193. col_df["ind"] = np.arange(len(col_df))
  194. col_indexes = col_df.join(upd_samples.columns.to_frame()[[]].copy()).ind.to_list()
  195. return self.stable_shap_values[row_indexes][:, col_indexes]
  196. def filter_shap_by_data_samples(self, data: ExpressionDataset):
  197. return self.filter_shap(lambda s: s.join(data.samples[[]], how="inner"))
  198. def filter_shap_by_data_samples_column(self, data: ExpressionDataset, column, values: List[str]):
  199. return self.filter_shap_by_data_samples_column(data.by_samples.collect(lambda s: s[column].isin(values)))
  200. def filter_shap_by_data_tissues(self, data: ExpressionDataset, tissues: List[str]):
  201. return self.filter_shap_by_data_samples_column("tissue", tissues)
  202. def filter_shap_by_data_species(self, data: ExpressionDataset, species: List[str]):
  203. return self.filter_shap_by_data_samples_column("species", species)
  204. def _plot_heatmap_(self,
  205. shap_explanation: Union[shap.Explanation, List[shap.Explanation]],
  206. gene_names: bool = True,
  207. max_display=30,
  208. figsize=(14, 8),
  209. sort_by_clust: bool = True,
  210. save: Path = None):
  211. value = shap_explanation if isinstance(shap_explanation, shap.Explanation) else sum(shap_explanation) / len(shap_explanation)
  212. if gene_names:
  213. value.feature_names = self.feature_names
  214. if sort_by_clust:
  215. shap.plots.heatmap(value, max_display=max_display, show=False)
  216. else:
  217. shap.plots.heatmap(value, max_display=max_display, show=False, instance_order=value.sum(1))
  218. return self.make_figure(save, figsize=figsize)
  219. def plot_heatmap(self, gene_names: bool = True, max_display=30, figsize=(14,8), sort_by_clust: bool = True, save: Path = None) -> matplotlib.figure.Figure:
  220. return self._plot_heatmap_(self.explanation_mean, gene_names, max_display, figsize, sort_by_clust, save)
  221. def _plot_decision_(self, expected_value: float, shap_values: List[np.ndarray] or np.ndarray, title: str = None, gene_names: bool = True,
  222. auto_size_plot: bool = True,
  223. minimum: int = 0.0, maximum: int = 0.0, feature_display_range = None, save: Path = None):
  224. #shap.summary_plot(shap_values, self.partitions.X, show=False)
  225. feature_names = None if gene_names is False else self.feature_names
  226. min_max = (self.partitions.data.y.min(), self.partitions.data.y.max())
  227. print(f"min_max dataset values: {min_max}")
  228. xlim = (min(min_max[0], minimum), max(min_max[1], maximum))
  229. shap.decision_plot(expected_value, shap_values, xlim=xlim, feature_names=feature_names.tolist(), title=title,
  230. auto_size_plot=auto_size_plot, feature_display_range=feature_display_range, show=False)
  231. return self.make_figure(save)
  232. def plot_decision(self, save: Path = None, feature_display_range = None):
  233. return self._plot_decision_(self.expected_values_mean, self.stable_shap_values, True, save, feature_display_range=feature_display_range)
  234. def data_for_interaction_heatmap(self, stable_interaction_values, max: int = 15, round: int = 4) -> Tuple[np.ndarray, np.ndarray]:
  235. abs_int = np.abs(stable_interaction_values).mean(axis=0).round(round)
  236. abs_int[np.diag_indices_from(abs_int)] = 0
  237. inds = np.argsort(-abs_int.sum(axis=0))[:max+1]
  238. feature_names: np.ndarray = self.feature_names[inds]
  239. return abs_int[inds, :][:, inds], feature_names
  240. def __plot_interactions__(self, stable_interaction_values, max: int = 15,
  241. round: int = 4, colorscale = red_blue,
  242. width: int = None, height: int = None,
  243. title="Interactions plot",
  244. axis_title: str = "Features",
  245. title_font_size = 18, save: Path = None
  246. ):
  247. import plotly.graph_objects as go
  248. abs_int, feature_names = self.data_for_interaction_heatmap(stable_interaction_values, max, round)
  249. data=go.Heatmap(
  250. z=abs_int,
  251. x=feature_names,
  252. y=feature_names,
  253. xtype="scaled",
  254. ytype="scaled",
  255. colorscale=colorscale)
  256. layout = go.Layout(
  257. title=title,
  258. hovermode='closest',
  259. autosize=True,
  260. paper_bgcolor='rgba(0,0,0,0)',
  261. plot_bgcolor='rgba(0,0,0,0)',
  262. xaxis=dict(zeroline=False,side="top", title_text=axis_title, showgrid=False),
  263. yaxis=dict(zeroline=False, autorange='reversed', scaleanchor="x", scaleratio=1, title_text=axis_title, showgrid=False),
  264. font = {"size": title_font_size}
  265. )
  266. fig = go.Figure(data=data, layout=layout)
  267. if height is not None:
  268. width = height if width is None else width
  269. fig.update_layout(
  270. autosize=False,
  271. width=width,
  272. height=height
  273. )
  274. if save is not None:
  275. fig.write_image(str(save))
  276. return fig
  277. def plot_interactions(self, max: int = 15,
  278. round: int = 4, colorscale = red_blue,
  279. width: int = None, height: int = None,
  280. title="Interactions plot",
  281. axis_title: str = "Features",
  282. title_font_size = 18, save: Path = None
  283. ):
  284. return self.__plot_interactions__(self.stable_interaction_values, max, round, colorscale, width, height, title, axis_title, title_font_size, save)
  285. def plot_fold_decision(self, num: int):
  286. assert num < len(self.folds), "index should be withing folds range!"
  287. f = self.folds[num]
  288. return self._plot_decision_(f.expected_value, f.shap_values)
  289. def plot_waterfall(self, index: Union[int, str], save: Path = None, max_display = 10, show: bool = False):
  290. return self.__plot_waterfall__(index, self.stable_shap_values, save, max_display, show)
  291. def __plot_waterfall__(self, index: Union[int, str], shap_values, save: Path = None, max_display = 10, show: bool = False):
  292. if isinstance(index, int):
  293. ind = index
  294. value = self.partitions.Y.iloc[index].values[0]
  295. else:
  296. ind = self.partitions.Y.index.get_loc(index)
  297. value = self.partitions.Y.loc[index].values[0]
  298. shap.plots._waterfall.waterfall_legacy(value, shap_values[ind], feature_names = self.feature_names, max_display=max_display, show=show)
  299. return self.make_figure(save)
  300. def plot_dependency(self, feature: str, interaction_index:str = "auto", save: Path = None):
  301. shap.dependence_plot(feature, self.stable_shap_values, self.partitions.X, feature_names=self.feature_names, interaction_index=interaction_index)
  302. return self.make_figure(save)
  303. def plot_fold_interactions(self, num: int, gene_names: bool = True, save: Path = None):
  304. f = self.folds[num]
  305. return self._plot_decision_(f.expected_value, f.interaction_values, gene_names, save)
  306. def plot(self, gene_names: bool = True, save: Path = None,
  307. title=None, max_display=100, layered_violin_max_num_bins = 20,
  308. plot_type=None, color=None, axis_color="#333333", alpha=1, show=True, class_names=None):
  309. return self._plot_(self.stable_shap_values, gene_names, save, title, max_display,
  310. layered_violin_max_num_bins, plot_type, color, axis_color, alpha, class_names)
  311. def plot_folds(self, names: bool = True, save: Path = None, title=None,
  312. max_display=100, layered_violin_max_num_bins = 20,
  313. plot_type=None, color=None, axis_color="#333333", alpha=1):
  314. class_names = ["fold_"+str(i) for i in range(len(self.shap_values))]
  315. return self._plot_(self.shap_values, names, save, title, max_display,
  316. layered_violin_max_num_bins, plot_type, color, axis_color, alpha, class_names = class_names)
  317. def plot_one_fold(self, num: int, names: bool = True, save: Path = None, title=None,
  318. max_display=100, layered_violin_max_num_bins = 20,
  319. plot_type=None, color=None, axis_color="#333333", alpha=1):
  320. assert num < len(self.shap_values), f"there are no shap values for fold {str(num)}!"
  321. return self._plot_(self.shap_values[num], names, save, title, max_display,
  322. layered_violin_max_num_bins, plot_type, color, axis_color, alpha)
  323. def _repr_html_(self):
  324. hold_metrics = self.hold_out_metrics._repr_html_() if self.partitions.has_hold_out else ""
  325. return f"<table border='2'>" \
  326. f"<caption><h3>Feature selection results</h3><caption>" \
  327. f"<tr style='text-align:center'><th>selected</th><th>metrics</th><th>hold out metrics</th></tr>" \
  328. f"<tr><td>{self.selected._repr_html_()}</th><th>{self.metrics_df._repr_html_()}</th><th>{ hold_metrics}</th></tr>" \
  329. f"</table>"
  330. @cached_property
  331. def selected_shap(self):
  332. return self.selected.join(self.shap_values.T.set_index())
  333. @dataclass
  334. class FeatureSummary:
  335. results: List[FeatureResults]
  336. nan_as_zero: bool = True
  337. def filter_explanation(self, filter: Callable[[pd.DataFrame], pd.DataFrame]) -> shap.Explanation:
  338. exp: shap.Explanation = self.mean_shap_values.copy()
  339. return self.first.filter_explanation(filter)
  340. def filter_shap(self, filter: Callable[[pd.DataFrame], pd.DataFrame]) -> np.ndarray:
  341. return self.first.filter_shap(filter)
  342. def filter_shap_by_data_samples(self, data: ExpressionDataset):
  343. return self.first.filter_shap_by_data_samples(data)
  344. def filter_shap_by_data_tissues(self, data: ExpressionDataset, tissues: List[str]):
  345. return self.first.filter_shap_by_data_tissues(data, tissues)
  346. def filter_shap_by_data_species(self, data: ExpressionDataset, species: List[str]):
  347. return self.first.filter_shap_by_data_species(data, species)
  348. @cached_property
  349. def explanations(self) -> List[shap.Explanation]:
  350. return [r.explanation_mean for r in self.results]
  351. @cached_property
  352. def explanation_mean(self) -> shap.Explanation:
  353. return sum(self.explanations) / len(self.explanations)
  354. def write(self, folder: Path, name: str, with_folds: bool = True, folds_name: str = None, repeat_prefix: str = None) -> Path:
  355. folds_name = name if folds_name is None else folds_name
  356. folder.mkdir(exist_ok=True)
  357. for i, r in enumerate(self.results):
  358. sub = str(i) if repeat_prefix is None else f"{repeat_prefix}_{i}"
  359. repeat = folder / sub
  360. repeat.mkdir(exist_ok=True)
  361. r.write(repeat, name, with_folds=with_folds, folds_name=folds_name)
  362. return folder
  363. def write_folds(self, folder: Path, name: str, repeat_prefix: str = None) -> Path:
  364. folder.mkdir(exist_ok=True)
  365. for i, r in enumerate(self.results):
  366. sub = str(i) if repeat_prefix is None else f"{repeat_prefix}_{i}"
  367. repeat = folder / sub
  368. repeat.mkdir(exist_ok=True)
  369. r.partitions.write(repeat, name)
  370. return folder
  371. def write_partitions(self, folder: Path, name: str, repeat_prefix: str = None) -> Path:
  372. folder.mkdir(exist_ok=True)
  373. for i, r in enumerate(self.results):
  374. sub = str(i) if repeat_prefix is None else f"{repeat_prefix}_{i}"
  375. repeat = folder / sub
  376. repeat.mkdir(exist_ok=True)
  377. r.partitions.write(repeat, name)
  378. return folder
  379. @property
  380. def first(self) -> FeatureResults:
  381. return self.results[0]
  382. @property
  383. def partitions(self):
  384. return self.first.partitions
  385. @cached_property
  386. def expected_values_mean(self):
  387. return np.mean([r.expected_values_mean for r in self.results])
  388. @cached_property
  389. def feature_names(self) -> np.ndarray:
  390. return self.first.feature_names
  391. @staticmethod
  392. def concat(results: Union[Dict[str, 'FeatureSummary'], List['FeatureSummary']], min_repeats: int):
  393. if isinstance(results, Dict):
  394. return FeatureSummary.concat([v for k, v in results.items()], min_repeats)
  395. else:
  396. return pd.concat([r.symbols_repeated(min_repeats) for r in results]).drop_duplicates()
  397. @property
  398. def features(self):
  399. return self.results[0].partitions.features
  400. @property
  401. def metrics(self) -> Metrics:
  402. return Metrics.to_dataframe([r.metrics for r in self.results])
  403. @property
  404. def to_predict(self):
  405. return self.results[0].to_predict
  406. @cached_property
  407. def metrics_average(self) -> Metrics:
  408. return Metrics.average([r.metrics_average for r in self.results])
  409. @cached_property
  410. def validation_metrics_average(self) -> Metrics:
  411. return Metrics.average([r.validation_metrics for r in self.results])
  412. @cached_property
  413. def kendall_tau_abs_mean(self):
  414. return np.mean(np.absolute(np.array([r.kendall_tau_abs_mean for r in self.results])))
  415. @property
  416. def metrics(self) -> pd.DataFrame:
  417. return pd.concat([r.metrics for r in self.results])
  418. @property
  419. def validation_metrics(self) -> pd.DataFrame:
  420. return pd.concat([r.validation_metrics for r in self.results])
  421. @property
  422. def hold_out_metrics(self) -> pd.DataFrame:
  423. return pd.concat([r.hold_out_metrics for r in self.results])
  424. @cached_property
  425. def shap_values(self) -> List[np.ndarray]:
  426. return [r.stable_shap_values for r in self.results]
  427. @cached_property
  428. def stable_shap_values(self):
  429. return np.mean(np.nan_to_num(self.shap_values, 0.0), axis=0) if self.nan_as_zero else np.nanmean(self.shap_values, axis=0)
  430. @cached_property
  431. def stable_shap_dataframe(self):
  432. return pd.DataFrame(self.stable_shap_values, index=self.partitions.X.index, columns=self.partitions.X.columns)
  433. @cached_property
  434. def stable_shap_dataframe_named(self):
  435. return pd.DataFrame(self.stable_shap_values, index=self.partitions.X.index, columns=self.feature_names)
  436. @cached_property
  437. def interaction_values(self) -> List[np.ndarray]:
  438. return [f.stable_interaction_values for f in self.results]
  439. @cached_property
  440. def stable_interaction_values(self):
  441. return np.mean(np.nan_to_num(self.interaction_values, 0.0), axis=0) if self.nan_as_zero else np.nanmean(self.interaction_values, axis=0)
  442. @property
  443. def MSE(self) -> float:
  444. return self.metrics_average.MSE
  445. @property
  446. def MAE(self) -> float:
  447. return self.metrics_average.MAE
  448. @property
  449. def R2(self) -> float:
  450. return self.metrics_average.R2
  451. @property
  452. def huber(self) -> float:
  453. return self.metrics_average.huber
  454. #intersection_percentage: float = 1.0
  455. def select_repeated(self, min_repeats: int):
  456. return self.selected[self.selected.repeats >= min_repeats]
  457. def symbols_repeated(self, min_repeats: int = 2) -> pd.Series:
  458. return self.select_repeated(min_repeats).symbol
  459. @property
  460. def all_symbols(self):
  461. return pd.concat([r.selected[["symbol"]] for r in self.results], axis=0).drop_duplicates()
  462. def select_symbols(self, repeats: int = None):
  463. return self.selected.symbol if repeats is None else self.select_repeated(repeats = repeats).symbol
  464. @cached_property
  465. def selected(self):
  466. first = self.results[0]
  467. result: pd.DataFrame = first.selected[[]]#.selected[["symbol"]]
  468. pref: str = self.features.importance_type if len([c for c in self.results[0].selected.columns if self.features.importance_type in c])>0 else "shap"
  469. for i, r in enumerate(self.results):
  470. c_shap = f"{pref}_{i}"
  471. c_tau = f"kendall_tau_{i}"
  472. res = r.selected.rename(columns=
  473. {f"{pref}_absolute_sum_to_{self.to_predict}": c_shap,
  474. f"{self.features.importance_type}_score_to_{self.to_predict}": c_shap,
  475. f"kendall_tau_to_{self.to_predict}": c_tau,
  476. f"shap_mean": f"shap_mean_{i}"}
  477. )
  478. res[f"in_fold_{i}"] = 1
  479. result = result.join(res[[c_shap, c_tau]], how="outer")
  480. pre_cols = result.columns.to_list()
  481. result["repeats"] = result.count(axis=1) / 2.0
  482. result["mean_abs_shap"] = result[[col for col in result.columns if pref in col]].fillna(0.0).mean(axis=1)
  483. result["shap_mean"] = result[[col for col in result.columns if "shap_mean" in col]].fillna(0.0).mean(axis=1)
  484. result["mean_kendall_tau"] = result[[col for col in result.columns if "kendall_tau" in col]].mean(skipna = True, axis=1)
  485. new_cols = ["repeats", "mean_abs_shap", "mean_kendall_tau"]
  486. cols = new_cols + pre_cols
  487. return self.all_symbols.join(result[cols], how="right").sort_values(by=["repeats", "mean_abs_shap", "mean_kendall_tau"], ascending=False)
  488. def _repr_html_(self):
  489. hold_metrics = self.hold_out_metrics._repr_html_() if self.partitions.has_hold_out else ""
  490. return f"<table border='2'>" \
  491. f"<caption><h3>Feature selection results</h3><caption>" \
  492. f"<tr style='text-align:center'><th>selected</th><th>metrics</th><th>hold out metrics</th></tr>" \
  493. f"<tr><td>{self.selected._repr_html_()}</th><th>{self.metrics._repr_html_()}</th><th>{hold_metrics}</th></tr>" \
  494. f"</table>"
  495. def plot_heatmap(self,
  496. gene_names: bool = True,
  497. max_display: int = 30,
  498. figsize: Tuple[float, float] = (14,9),
  499. sort_by_clust: bool = False,
  500. save: Path = None,
  501. custom_explanation: shap.Explanation = None
  502. ):
  503. explanation = self.explanation_mean if custom_explanation is None else custom_explanation
  504. return self.first._plot_heatmap_(explanation, gene_names, max_display, figsize, sort_by_clust, save)
  505. def plot_waterfall(self, index: Union[int, str], save: Path = None, max_display = 10, show: bool = False):
  506. return self.first.__plot_waterfall__(index, self.stable_shap_values, save, max_display, show)
  507. def plot_dependency(self, feature: str, interaction_index:str = "auto", save: Path = None):
  508. shap.dependence_plot(feature, self.stable_shap_values, self.partitions.X, feature_names=self.feature_names, interaction_index=interaction_index)
  509. return self.first.make_figure(save)
  510. def plot_interactions(self, max: int = 15,
  511. round: int = 4, colorscale = red_blue,
  512. width: int = None, height: int = None,
  513. title="Interactions plot",
  514. axis_title: str = "Features",
  515. title_font_size = 18, save: Path = None
  516. ):
  517. return self.first.__plot_interactions__(self.stable_interaction_values, max, round, colorscale, width, height, title, axis_title, title_font_size, save)
  518. def plot(self,
  519. gene_names: bool = True,
  520. save: Path = None,
  521. max_display=50,
  522. title=None,
  523. plot_size = 0.5,
  524. layered_violin_max_num_bins = 20,
  525. plot_type=None,
  526. color=None,
  527. axis_color="#333333",
  528. alpha=1,
  529. class_names=None,
  530. custom_shap_values: np.ndarray = None,
  531. custom_x: pd.DataFrame = None
  532. ):
  533. shap_values = self.stable_shap_values if custom_shap_values is None else custom_shap_values
  534. return self.first._plot_(shap_values, gene_names, save, max_display, title,
  535. layered_violin_max_num_bins, plot_type, color, axis_color, alpha, class_names = class_names, plot_size=plot_size)
  536. def plot_interaction_decision(self, title: str = None,
  537. minimum: float = 0.0, maximum: float = 0.0,
  538. feature_display_range = None,
  539. auto_size_plot: bool = True,
  540. save: Path = None):
  541. return self.first._plot_decision_(self.expected_values_mean, self.stable_interaction_values, title, True, minimum= minimum, maximum= maximum,
  542. feature_display_range = feature_display_range, auto_size_plot = auto_size_plot, save = save)
  543. def plot_decision(self,
  544. title: str = None,
  545. minimum: float = 0.0,
  546. maximum: float = 0.0,
  547. feature_display_range = None,
  548. auto_size_plot: bool = True,
  549. save: Path = None,
  550. custom_shap_values: np.ndarray = None,
  551. ):
  552. shap_values = self.stable_shap_values if custom_shap_values is None else custom_shap_values
  553. return self.first._plot_decision_(self.expected_values_mean, shap_values, title, True, minimum= minimum, maximum= maximum,
  554. feature_display_range = feature_display_range, auto_size_plot = auto_size_plot, save = save)
  555. @dataclass
  556. class ShapSelector(TransformerMixin):
  557. def fit(self, folds_with_params: Tuple[List[Fold], Dict], y=None) -> 'ShapSelector':
  558. return self
  559. @logger.catch
  560. def transform(self, folds_with_params: Tuple[List[Fold], Dict]) -> FeatureResults:
  561. folds, parameters = folds_with_params
  562. fold_shap_values = [f.shap_values for f in folds]
  563. partitions = folds[0].partitions
  564. # calculate shap values out of fold
  565. mean_shap_values = np.nanmean(fold_shap_values, axis=0)
  566. shap_values_transposed = mean_shap_values.T
  567. fold_number = partitions.n_cv_folds
  568. X_transposed = partitions.X_T.values
  569. select_by_shap = partitions.features.select_by == "shap"
  570. score_name = 'shap_absolute_sum_to_' + partitions.features.to_predict if select_by_shap else f'{partitions.features.importance_type}_score_to_' + partitions.features.to_predict
  571. kendal_tau_name = 'kendall_tau_to_' + partitions.features.to_predict
  572. # get features that have stable weight across self.bootstraps
  573. output_features_by_weight = []
  574. for i, column in enumerate(folds[0].shap_dataframe.columns):
  575. non_zero_cols = 0
  576. cols = []
  577. for f in folds:
  578. weight = f.shap_absolute_mean[column] if select_by_shap else f.feature_weights[i] #folds[0].shap_absolute_sum[column]
  579. cols.append(weight)
  580. if weight != 0:
  581. non_zero_cols += 1
  582. if non_zero_cols == fold_number:
  583. if 'ENSG' in partitions.X.columns[
  584. i]: # TODO: change from hard-coded ENSG checkup to something more meaningful
  585. output_features_by_weight.append({
  586. 'ensembl_id': partitions.X.columns[i],
  587. score_name: np.mean(cols),
  588. "shap_mean": np.mean(shap_values_transposed[i]),
  589. # 'name': partitions.X.columns[i], #ensemble_data.gene_name_of_gene_id(X.columns[i]),
  590. kendal_tau_name: kendalltau(shap_values_transposed[i], X_transposed[i], nan_policy='omit')[0]
  591. })
  592. if(len(output_features_by_weight)==0):
  593. logger.error(f"could not find genes which are in all folds, creating empty dataframe instead!")
  594. empty_selected = pd.DataFrame(columns=["symbol", score_name, kendal_tau_name])
  595. return FeatureResults(empty_selected, folds, partitions, parameters)
  596. selected_features = pd.DataFrame(output_features_by_weight)
  597. selected_features = selected_features.set_index("ensembl_id")
  598. if isinstance(partitions.data.genes_meta, pd.DataFrame):
  599. selected_features = partitions.data.genes_meta.drop(columns=["species"]) \
  600. .join(selected_features, how="inner") \
  601. .sort_values(by=[score_name], ascending=False)
  602. #selected_features.index = "ensembl_id"
  603. results = FeatureResults(selected_features, folds, partitions, parameters)
  604. logger.info(f"Metrics: \n{results.metrics_average}")
  605. return results
  606. # from shap import Explanation
Tip!

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

Comments

Loading...