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

analyze_helper.html 26 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
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
  6. <meta name="generator" content="pdoc 0.7.2" />
  7. <title>src.analyze_helper API documentation</title>
  8. <meta name="description" content="" />
  9. <link href='https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css' rel='stylesheet'>
  10. <link href='https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/8.0.0/sanitize.min.css' rel='stylesheet'>
  11. <link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css" rel="stylesheet">
  12. <style>.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{font-weight:bold}#index h4 + ul{margin-bottom:.6em}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
  13. <style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
  14. <style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
  15. </head>
  16. <body>
  17. <main>
  18. <article id="content">
  19. <header>
  20. <h1 class="title">Module <code>src.analyze_helper</code></h1>
  21. </header>
  22. <section id="section-intro">
  23. <details class="source">
  24. <summary>
  25. <span>Expand source code</span>
  26. </summary>
  27. <pre><code class="python">from matplotlib import pyplot as plt
  28. import os
  29. from os.path import join as oj
  30. import numpy as np
  31. import pandas as pd
  32. import data
  33. from sklearn.model_selection import KFold
  34. from colorama import Fore
  35. import pickle as pkl
  36. import config
  37. import viz
  38. from config import *
  39. def load_results(out_dir):
  40. r = []
  41. for fname in os.listdir(out_dir):
  42. d = pkl.load(open(oj(out_dir, fname), &#39;rb&#39;))
  43. metrics = {k: d[&#39;cv&#39;][k] for k in d[&#39;cv&#39;].keys() if not &#39;curve&#39; in k}
  44. num_pts_by_fold_cv = d[&#39;num_pts_by_fold_cv&#39;]
  45. out = {k: np.average(metrics[k], weights=num_pts_by_fold_cv) for k in metrics}
  46. out.update({k + &#39;_std&#39;: np.std(metrics[k]) for k in metrics})
  47. out[&#39;model_type&#39;] = fname.replace(&#39;.pkl&#39;, &#39;&#39;) # d[&#39;model_type&#39;]
  48. imp_mat = np.array(d[&#39;imps&#39;][&#39;imps&#39;])
  49. imp_mu = imp_mat.mean(axis=0)
  50. imp_sd = imp_mat.std(axis=0)
  51. feat_names = d[&#39;feat_names_selected&#39;]
  52. out.update({feat_names[i] + &#39;_f&#39;: imp_mu[i] for i in range(len(feat_names))})
  53. out.update({feat_names[i] + &#39;_std_f&#39;: imp_sd[i] for i in range(len(feat_names))})
  54. r.append(pd.Series(out))
  55. r = pd.concat(r, axis=1, sort=False).T.infer_objects()
  56. r = r.reindex(sorted(r.columns), axis=1) # sort the column names
  57. r = r.round(3)
  58. r = r.set_index(&#39;model_type&#39;)
  59. return r
  60. def get_data_over_folds(model_names: list, out_dir: str, cell_nums: pd.Series, X, y, outcome_def=&#39;y_consec_sig&#39;, dset=&#39;clath_aux+gak_a7d2&#39;):
  61. &#39;&#39;&#39;Returns predictions/labels over folds in the dataset
  62. Params
  63. ------
  64. cell_nums: pd.Series
  65. equivalent to df.cell_num
  66. Returns
  67. -------
  68. d_full_cv: pd.DataFrame
  69. n rows, one for each data point in the training set (over all folds)
  70. 2 columns for each model, one for predictions, and one for predicted probabilities
  71. idxs_cv: np.array
  72. indexes corresponding locations of the validation set
  73. for example, df.y_thresh.iloc[idxs_cv] would yield all the labels corresponding to the cv preds
  74. &#39;&#39;&#39;
  75. # split testing data based on cell num
  76. d = {}
  77. cell_nums_train = config.DSETS[dset][&#39;train&#39;]
  78. kf = KFold(n_splits=len(cell_nums_train))
  79. idxs_cv = []
  80. # get predictions over all folds and save into a dict
  81. if not type(model_names) == &#39;list&#39; and not &#39;ndarray&#39; in str(type(model_names)):
  82. model_names = [model_names]
  83. for i, model_name in enumerate(model_names):
  84. results_individual = pkl.load(open(f&#39;{out_dir}/{model_name}.pkl&#39;, &#39;rb&#39;))
  85. fold_num = 0
  86. for cv_idx, cv_val_idx in kf.split(cell_nums_train):
  87. # get sample indices
  88. idxs_val_cv = cell_nums.isin(cell_nums_train[np.array(cv_val_idx)])
  89. X_val_cv, Y_val_cv = X[idxs_val_cv], y[idxs_val_cv]
  90. # get predictions
  91. preds, preds_proba = analyze_individual_results(results_individual, X_val_cv, Y_val_cv,
  92. print_results=False, plot_results=False,
  93. model_cv_fold=fold_num)
  94. d[f&#39;{model_name}_{fold_num}&#39;] = preds
  95. d[f&#39;{model_name}_{fold_num}_proba&#39;] = preds_proba
  96. if i == 0:
  97. idxs_cv.append(np.arange(X.shape[0])[idxs_val_cv])
  98. fold_num += 1
  99. # concatenate over folds
  100. d2 = {}
  101. for model_name in model_names:
  102. d2[model_name] = np.hstack([d[k] for k in d.keys() if model_name in k and not &#39;proba&#39; in k])
  103. d2[model_name + &#39;_proba&#39;] = np.hstack([d[k] for k in d.keys() if model_name in k and &#39;proba&#39; in k])
  104. return pd.DataFrame.from_dict(d2), np.hstack(idxs_cv)
  105. def analyze_individual_results(results, X_test, Y_test, print_results=False, plot_results=False, model_cv_fold=0):
  106. scores_cv = results[&#39;cv&#39;]
  107. imps = results[&#39;imps&#39;]
  108. m = imps[&#39;model&#39;][model_cv_fold]
  109. preds = m.predict(X_test[results[&#39;feat_names_selected&#39;]])
  110. try:
  111. preds_proba = m.predict_proba(X_test[results[&#39;feat_names_selected&#39;]])[:, 1]
  112. except:
  113. preds_proba = preds
  114. if print_results:
  115. print(Fore.CYAN + f&#39;{&#34;metric&#34;:&lt;25}\tvalidation&#39;) # \ttest&#39;)
  116. for s in results[&#39;metrics&#39;]:
  117. if not &#39;curve&#39; in s:
  118. print(Fore.WHITE + f&#39;{s:&lt;25}\t{np.mean(scores_cv[s]):.3f} ~ {np.std(scores_cv[s]):.3f}&#39;)
  119. # print(Fore.WHITE + f&#39;{s:&lt;25}\t{np.mean(scores_cv[s]):.3f} ~ {np.std(scores_cv[s]):.3f}\t{np.mean(scores_test[s]):.3f} ~ {np.std(scores_test[s]):.3f}&#39;)
  120. print(Fore.CYAN + &#39;\nfeature importances&#39;)
  121. imp_mat = np.array(imps[&#39;imps&#39;])
  122. imp_mu = imp_mat.mean(axis=0)
  123. imp_sd = imp_mat.std(axis=0)
  124. for i, feat_name in enumerate(results[&#39;feat_names_selected&#39;]):
  125. print(Fore.WHITE + f&#39;{feat_name:&lt;25}\t{imp_mu[i]:.3f} ~ {imp_sd[i]:.3f}&#39;)
  126. if plot_results:
  127. # print(m.coef_)
  128. plt.figure(figsize=(10, 3), dpi=140)
  129. R, C = 1, 3
  130. plt.subplot(R, C, 1)
  131. # print(X_test.shape, results[&#39;feat_names&#39;])
  132. viz.plot_confusion_matrix(Y_test, preds, classes=np.array([&#39;Failure&#39;, &#39;Success&#39;]))
  133. plt.subplot(R, C, 2)
  134. prec, rec, thresh = scores_test[&#39;precision_recall_curve&#39;][0]
  135. plt.plot(rec, prec)
  136. plt.xlim((-0.1, 1.1))
  137. plt.ylim((-0.1, 1.1))
  138. plt.ylabel(&#39;Precision&#39;)
  139. plt.xlabel(&#39;Recall&#39;)
  140. plt.subplot(R, C, 3)
  141. plt.hist(preds_proba[Y_test == 0], alpha=0.5, label=&#39;Failure&#39;)
  142. plt.hist(preds_proba[Y_test == 1], alpha=0.5, label=&#39;Success&#39;)
  143. plt.xlabel(&#39;Predicted probability&#39;)
  144. plt.ylabel(&#39;Count&#39;)
  145. plt.legend()
  146. plt.tight_layout()
  147. plt.show()
  148. return preds, preds_proba
  149. def load_results_many_models(out_dir, model_names, X_test, Y_test):
  150. d = {}
  151. for i, model_name in enumerate(model_names):
  152. results_individual = pkl.load(open(oj(out_dir, f&#39;{model_name}.pkl&#39;), &#39;rb&#39;))
  153. preds, preds_proba = analyze_individual_results(results_individual, X_test, Y_test,
  154. print_results=False, plot_results=False)
  155. d[model_name] = preds
  156. d[model_name + &#39;_proba&#39;] = preds_proba
  157. d[model_name + &#39;_errs&#39;] = preds != Y_test
  158. df_preds = pd.DataFrame.from_dict(d)
  159. return df_preds
  160. # normalize and store
  161. def normalize(df, outcome_def):
  162. X = df[data.get_feature_names(df)]
  163. X_mean = X.mean()
  164. X_std = X.std()
  165. ks = list(X.keys())
  166. norms = {ks[i]: {&#39;mu&#39;: X_mean[i], &#39;std&#39;: X_std[i]}
  167. for i in range(len(ks))}
  168. X = (X - X_mean) / X_std
  169. y = df[outcome_def].values
  170. return X, y, norms
  171. def normalize_and_predict(m0, feat_names_selected, dset_name, normalize_by_train,
  172. exclude_easy_tracks=False, outcome_def=&#39;y_consec_thresh&#39;):
  173. df_new = data.get_data(dset=dset_name, use_processed=True,
  174. use_processed_dicts=True, outcome_def=outcome_def,
  175. previous_meta_file=oj(DIR_PROCESSED,
  176. &#39;metadata_clath_aux+gak_a7d2.pkl&#39;))
  177. if exclude_easy_tracks:
  178. df_new = df_new[df_new[&#39;valid&#39;]] # exclude test cells, short/long tracks, hotspots
  179. # impute (only does anything for dynamin data)
  180. df_new = df_new.fillna(df_new.median())
  181. X_new = df_new[data.get_feature_names(df_new)]
  182. if normalize_by_train:
  183. X_new = (X_new - X_mean_train) / X_std_train
  184. else:
  185. X_new = (X_new - X_new.mean()) / X_new.std()
  186. y_new = df_new[outcome_def].values
  187. preds_new = m0.predict(X_new[feat_names_selected])
  188. preds_proba_new = m0.predict_proba(X_new[feat_names_selected])[:, 1]
  189. Y_maxes = df_new[&#39;Y_max&#39;]
  190. return df_new, y_new, preds_new, preds_proba_new, Y_maxes
  191. def calc_errs(preds, y_full_cv):
  192. tp = np.logical_and(preds == 1, y_full_cv == 1)
  193. tn = np.logical_and(preds == 0, y_full_cv == 0)
  194. fp = preds &gt; y_full_cv
  195. fn = preds &lt; y_full_cv
  196. return tp, tn, fp, fn</code></pre>
  197. </details>
  198. </section>
  199. <section>
  200. </section>
  201. <section>
  202. </section>
  203. <section>
  204. <h2 class="section-title" id="header-functions">Functions</h2>
  205. <dl>
  206. <dt id="src.analyze_helper.analyze_individual_results"><code class="name flex">
  207. <span>def <span class="ident">analyze_individual_results</span></span>(<span>results, X_test, Y_test, print_results=False, plot_results=False, model_cv_fold=0)</span>
  208. </code></dt>
  209. <dd>
  210. <section class="desc"></section>
  211. <details class="source">
  212. <summary>
  213. <span>Expand source code</span>
  214. </summary>
  215. <pre><code class="python">def analyze_individual_results(results, X_test, Y_test, print_results=False, plot_results=False, model_cv_fold=0):
  216. scores_cv = results[&#39;cv&#39;]
  217. imps = results[&#39;imps&#39;]
  218. m = imps[&#39;model&#39;][model_cv_fold]
  219. preds = m.predict(X_test[results[&#39;feat_names_selected&#39;]])
  220. try:
  221. preds_proba = m.predict_proba(X_test[results[&#39;feat_names_selected&#39;]])[:, 1]
  222. except:
  223. preds_proba = preds
  224. if print_results:
  225. print(Fore.CYAN + f&#39;{&#34;metric&#34;:&lt;25}\tvalidation&#39;) # \ttest&#39;)
  226. for s in results[&#39;metrics&#39;]:
  227. if not &#39;curve&#39; in s:
  228. print(Fore.WHITE + f&#39;{s:&lt;25}\t{np.mean(scores_cv[s]):.3f} ~ {np.std(scores_cv[s]):.3f}&#39;)
  229. # print(Fore.WHITE + f&#39;{s:&lt;25}\t{np.mean(scores_cv[s]):.3f} ~ {np.std(scores_cv[s]):.3f}\t{np.mean(scores_test[s]):.3f} ~ {np.std(scores_test[s]):.3f}&#39;)
  230. print(Fore.CYAN + &#39;\nfeature importances&#39;)
  231. imp_mat = np.array(imps[&#39;imps&#39;])
  232. imp_mu = imp_mat.mean(axis=0)
  233. imp_sd = imp_mat.std(axis=0)
  234. for i, feat_name in enumerate(results[&#39;feat_names_selected&#39;]):
  235. print(Fore.WHITE + f&#39;{feat_name:&lt;25}\t{imp_mu[i]:.3f} ~ {imp_sd[i]:.3f}&#39;)
  236. if plot_results:
  237. # print(m.coef_)
  238. plt.figure(figsize=(10, 3), dpi=140)
  239. R, C = 1, 3
  240. plt.subplot(R, C, 1)
  241. # print(X_test.shape, results[&#39;feat_names&#39;])
  242. viz.plot_confusion_matrix(Y_test, preds, classes=np.array([&#39;Failure&#39;, &#39;Success&#39;]))
  243. plt.subplot(R, C, 2)
  244. prec, rec, thresh = scores_test[&#39;precision_recall_curve&#39;][0]
  245. plt.plot(rec, prec)
  246. plt.xlim((-0.1, 1.1))
  247. plt.ylim((-0.1, 1.1))
  248. plt.ylabel(&#39;Precision&#39;)
  249. plt.xlabel(&#39;Recall&#39;)
  250. plt.subplot(R, C, 3)
  251. plt.hist(preds_proba[Y_test == 0], alpha=0.5, label=&#39;Failure&#39;)
  252. plt.hist(preds_proba[Y_test == 1], alpha=0.5, label=&#39;Success&#39;)
  253. plt.xlabel(&#39;Predicted probability&#39;)
  254. plt.ylabel(&#39;Count&#39;)
  255. plt.legend()
  256. plt.tight_layout()
  257. plt.show()
  258. return preds, preds_proba</code></pre>
  259. </details>
  260. </dd>
  261. <dt id="src.analyze_helper.calc_errs"><code class="name flex">
  262. <span>def <span class="ident">calc_errs</span></span>(<span>preds, y_full_cv)</span>
  263. </code></dt>
  264. <dd>
  265. <section class="desc"></section>
  266. <details class="source">
  267. <summary>
  268. <span>Expand source code</span>
  269. </summary>
  270. <pre><code class="python">def calc_errs(preds, y_full_cv):
  271. tp = np.logical_and(preds == 1, y_full_cv == 1)
  272. tn = np.logical_and(preds == 0, y_full_cv == 0)
  273. fp = preds &gt; y_full_cv
  274. fn = preds &lt; y_full_cv
  275. return tp, tn, fp, fn</code></pre>
  276. </details>
  277. </dd>
  278. <dt id="src.analyze_helper.get_data_over_folds"><code class="name flex">
  279. <span>def <span class="ident">get_data_over_folds</span></span>(<span>model_names, out_dir, cell_nums, X, y, outcome_def='y_consec_sig', dset='clath_aux+gak_a7d2')</span>
  280. </code></dt>
  281. <dd>
  282. <section class="desc"><p>Returns predictions/labels over folds in the dataset
  283. Params</p>
  284. <hr>
  285. <dl>
  286. <dt><strong><code>cell_nums</code></strong> :&ensp;<code>pd.Series</code></dt>
  287. <dd>equivalent to df.cell_num</dd>
  288. </dl>
  289. <h2 id="returns">Returns</h2>
  290. <dl>
  291. <dt><strong><code>d_full_cv</code></strong> :&ensp;<code>pd.DataFrame</code></dt>
  292. <dd>n rows, one for each data point in the training set (over all folds)
  293. 2 columns for each model, one for predictions, and one for predicted probabilities</dd>
  294. <dt><strong><code>idxs_cv</code></strong> :&ensp;<code>np.array</code></dt>
  295. <dd>indexes corresponding locations of the validation set
  296. for example, df.y_thresh.iloc[idxs_cv] would yield all the labels corresponding to the cv preds</dd>
  297. </dl></section>
  298. <details class="source">
  299. <summary>
  300. <span>Expand source code</span>
  301. </summary>
  302. <pre><code class="python">def get_data_over_folds(model_names: list, out_dir: str, cell_nums: pd.Series, X, y, outcome_def=&#39;y_consec_sig&#39;, dset=&#39;clath_aux+gak_a7d2&#39;):
  303. &#39;&#39;&#39;Returns predictions/labels over folds in the dataset
  304. Params
  305. ------
  306. cell_nums: pd.Series
  307. equivalent to df.cell_num
  308. Returns
  309. -------
  310. d_full_cv: pd.DataFrame
  311. n rows, one for each data point in the training set (over all folds)
  312. 2 columns for each model, one for predictions, and one for predicted probabilities
  313. idxs_cv: np.array
  314. indexes corresponding locations of the validation set
  315. for example, df.y_thresh.iloc[idxs_cv] would yield all the labels corresponding to the cv preds
  316. &#39;&#39;&#39;
  317. # split testing data based on cell num
  318. d = {}
  319. cell_nums_train = config.DSETS[dset][&#39;train&#39;]
  320. kf = KFold(n_splits=len(cell_nums_train))
  321. idxs_cv = []
  322. # get predictions over all folds and save into a dict
  323. if not type(model_names) == &#39;list&#39; and not &#39;ndarray&#39; in str(type(model_names)):
  324. model_names = [model_names]
  325. for i, model_name in enumerate(model_names):
  326. results_individual = pkl.load(open(f&#39;{out_dir}/{model_name}.pkl&#39;, &#39;rb&#39;))
  327. fold_num = 0
  328. for cv_idx, cv_val_idx in kf.split(cell_nums_train):
  329. # get sample indices
  330. idxs_val_cv = cell_nums.isin(cell_nums_train[np.array(cv_val_idx)])
  331. X_val_cv, Y_val_cv = X[idxs_val_cv], y[idxs_val_cv]
  332. # get predictions
  333. preds, preds_proba = analyze_individual_results(results_individual, X_val_cv, Y_val_cv,
  334. print_results=False, plot_results=False,
  335. model_cv_fold=fold_num)
  336. d[f&#39;{model_name}_{fold_num}&#39;] = preds
  337. d[f&#39;{model_name}_{fold_num}_proba&#39;] = preds_proba
  338. if i == 0:
  339. idxs_cv.append(np.arange(X.shape[0])[idxs_val_cv])
  340. fold_num += 1
  341. # concatenate over folds
  342. d2 = {}
  343. for model_name in model_names:
  344. d2[model_name] = np.hstack([d[k] for k in d.keys() if model_name in k and not &#39;proba&#39; in k])
  345. d2[model_name + &#39;_proba&#39;] = np.hstack([d[k] for k in d.keys() if model_name in k and &#39;proba&#39; in k])
  346. return pd.DataFrame.from_dict(d2), np.hstack(idxs_cv)</code></pre>
  347. </details>
  348. </dd>
  349. <dt id="src.analyze_helper.load_results"><code class="name flex">
  350. <span>def <span class="ident">load_results</span></span>(<span>out_dir)</span>
  351. </code></dt>
  352. <dd>
  353. <section class="desc"></section>
  354. <details class="source">
  355. <summary>
  356. <span>Expand source code</span>
  357. </summary>
  358. <pre><code class="python">def load_results(out_dir):
  359. r = []
  360. for fname in os.listdir(out_dir):
  361. d = pkl.load(open(oj(out_dir, fname), &#39;rb&#39;))
  362. metrics = {k: d[&#39;cv&#39;][k] for k in d[&#39;cv&#39;].keys() if not &#39;curve&#39; in k}
  363. num_pts_by_fold_cv = d[&#39;num_pts_by_fold_cv&#39;]
  364. out = {k: np.average(metrics[k], weights=num_pts_by_fold_cv) for k in metrics}
  365. out.update({k + &#39;_std&#39;: np.std(metrics[k]) for k in metrics})
  366. out[&#39;model_type&#39;] = fname.replace(&#39;.pkl&#39;, &#39;&#39;) # d[&#39;model_type&#39;]
  367. imp_mat = np.array(d[&#39;imps&#39;][&#39;imps&#39;])
  368. imp_mu = imp_mat.mean(axis=0)
  369. imp_sd = imp_mat.std(axis=0)
  370. feat_names = d[&#39;feat_names_selected&#39;]
  371. out.update({feat_names[i] + &#39;_f&#39;: imp_mu[i] for i in range(len(feat_names))})
  372. out.update({feat_names[i] + &#39;_std_f&#39;: imp_sd[i] for i in range(len(feat_names))})
  373. r.append(pd.Series(out))
  374. r = pd.concat(r, axis=1, sort=False).T.infer_objects()
  375. r = r.reindex(sorted(r.columns), axis=1) # sort the column names
  376. r = r.round(3)
  377. r = r.set_index(&#39;model_type&#39;)
  378. return r</code></pre>
  379. </details>
  380. </dd>
  381. <dt id="src.analyze_helper.load_results_many_models"><code class="name flex">
  382. <span>def <span class="ident">load_results_many_models</span></span>(<span>out_dir, model_names, X_test, Y_test)</span>
  383. </code></dt>
  384. <dd>
  385. <section class="desc"></section>
  386. <details class="source">
  387. <summary>
  388. <span>Expand source code</span>
  389. </summary>
  390. <pre><code class="python">def load_results_many_models(out_dir, model_names, X_test, Y_test):
  391. d = {}
  392. for i, model_name in enumerate(model_names):
  393. results_individual = pkl.load(open(oj(out_dir, f&#39;{model_name}.pkl&#39;), &#39;rb&#39;))
  394. preds, preds_proba = analyze_individual_results(results_individual, X_test, Y_test,
  395. print_results=False, plot_results=False)
  396. d[model_name] = preds
  397. d[model_name + &#39;_proba&#39;] = preds_proba
  398. d[model_name + &#39;_errs&#39;] = preds != Y_test
  399. df_preds = pd.DataFrame.from_dict(d)
  400. return df_preds</code></pre>
  401. </details>
  402. </dd>
  403. <dt id="src.analyze_helper.normalize"><code class="name flex">
  404. <span>def <span class="ident">normalize</span></span>(<span>df, outcome_def)</span>
  405. </code></dt>
  406. <dd>
  407. <section class="desc"></section>
  408. <details class="source">
  409. <summary>
  410. <span>Expand source code</span>
  411. </summary>
  412. <pre><code class="python">def normalize(df, outcome_def):
  413. X = df[data.get_feature_names(df)]
  414. X_mean = X.mean()
  415. X_std = X.std()
  416. ks = list(X.keys())
  417. norms = {ks[i]: {&#39;mu&#39;: X_mean[i], &#39;std&#39;: X_std[i]}
  418. for i in range(len(ks))}
  419. X = (X - X_mean) / X_std
  420. y = df[outcome_def].values
  421. return X, y, norms</code></pre>
  422. </details>
  423. </dd>
  424. <dt id="src.analyze_helper.normalize_and_predict"><code class="name flex">
  425. <span>def <span class="ident">normalize_and_predict</span></span>(<span>m0, feat_names_selected, dset_name, normalize_by_train, exclude_easy_tracks=False, outcome_def='y_consec_thresh')</span>
  426. </code></dt>
  427. <dd>
  428. <section class="desc"></section>
  429. <details class="source">
  430. <summary>
  431. <span>Expand source code</span>
  432. </summary>
  433. <pre><code class="python">def normalize_and_predict(m0, feat_names_selected, dset_name, normalize_by_train,
  434. exclude_easy_tracks=False, outcome_def=&#39;y_consec_thresh&#39;):
  435. df_new = data.get_data(dset=dset_name, use_processed=True,
  436. use_processed_dicts=True, outcome_def=outcome_def,
  437. previous_meta_file=oj(DIR_PROCESSED,
  438. &#39;metadata_clath_aux+gak_a7d2.pkl&#39;))
  439. if exclude_easy_tracks:
  440. df_new = df_new[df_new[&#39;valid&#39;]] # exclude test cells, short/long tracks, hotspots
  441. # impute (only does anything for dynamin data)
  442. df_new = df_new.fillna(df_new.median())
  443. X_new = df_new[data.get_feature_names(df_new)]
  444. if normalize_by_train:
  445. X_new = (X_new - X_mean_train) / X_std_train
  446. else:
  447. X_new = (X_new - X_new.mean()) / X_new.std()
  448. y_new = df_new[outcome_def].values
  449. preds_new = m0.predict(X_new[feat_names_selected])
  450. preds_proba_new = m0.predict_proba(X_new[feat_names_selected])[:, 1]
  451. Y_maxes = df_new[&#39;Y_max&#39;]
  452. return df_new, y_new, preds_new, preds_proba_new, Y_maxes</code></pre>
  453. </details>
  454. </dd>
  455. </dl>
  456. </section>
  457. <section>
  458. </section>
  459. </article>
  460. <nav id="sidebar">
  461. <h1>Index</h1>
  462. <div class="toc">
  463. <ul></ul>
  464. </div>
  465. <ul id="index">
  466. <li><h3>Super-module</h3>
  467. <ul>
  468. <li><code><a title="src" href="index.html">src</a></code></li>
  469. </ul>
  470. </li>
  471. <li><h3><a href="#header-functions">Functions</a></h3>
  472. <ul class="">
  473. <li><code><a title="src.analyze_helper.analyze_individual_results" href="#src.analyze_helper.analyze_individual_results">analyze_individual_results</a></code></li>
  474. <li><code><a title="src.analyze_helper.calc_errs" href="#src.analyze_helper.calc_errs">calc_errs</a></code></li>
  475. <li><code><a title="src.analyze_helper.get_data_over_folds" href="#src.analyze_helper.get_data_over_folds">get_data_over_folds</a></code></li>
  476. <li><code><a title="src.analyze_helper.load_results" href="#src.analyze_helper.load_results">load_results</a></code></li>
  477. <li><code><a title="src.analyze_helper.load_results_many_models" href="#src.analyze_helper.load_results_many_models">load_results_many_models</a></code></li>
  478. <li><code><a title="src.analyze_helper.normalize" href="#src.analyze_helper.normalize">normalize</a></code></li>
  479. <li><code><a title="src.analyze_helper.normalize_and_predict" href="#src.analyze_helper.normalize_and_predict">normalize_and_predict</a></code></li>
  480. </ul>
  481. </li>
  482. </ul>
  483. </nav>
  484. </main>
  485. <footer id="footer">
  486. <p>Generated by <a href="https://pdoc3.github.io/pdoc"><cite>pdoc</cite> 0.7.2</a>.</p>
  487. </footer>
  488. <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
  489. <script>hljs.initHighlightingOnLoad()</script>
  490. </body>
  491. </html>
Tip!

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

Comments

Loading...