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

train_reg.html 32 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
  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.train_reg 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.train_reg</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">import os
  28. import pickle as pkl
  29. from os.path import join as oj
  30. import numpy as np
  31. import pandas as pd
  32. from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
  33. from sklearn.linear_model import LinearRegression, RidgeCV
  34. from sklearn.metrics import r2_score
  35. from sklearn.model_selection import KFold
  36. from sklearn.neural_network import MLPRegressor
  37. from sklearn.svm import SVR
  38. from sklearn.tree import DecisionTreeRegressor
  39. from statsmodels import robust
  40. import features
  41. import data
  42. import config
  43. from tqdm import tqdm
  44. from scipy.stats import pearsonr, kendalltau
  45. from neural_networks import neural_net_sklearn
  46. #cell_nums_train = np.array([1, 2, 3, 4, 5])
  47. #cell_nums_test = np.array([6])
  48. def add_robust_features(df):
  49. df[&#39;X_95_quantile&#39;] = np.array([np.quantile(df.iloc[i].X, 0.95) for i in range(len(df))])
  50. df[&#39;X_mad&#39;] = np.array([robust.mad(df.iloc[i].X) for i in range(len(df))])
  51. return df
  52. def log_transforms(df):
  53. df = add_robust_features(df)
  54. df[&#39;X_max_log&#39;] = np.log(df[&#39;X_max&#39;])
  55. df[&#39;X_95_quantile_log&#39;] = np.log(df[&#39;X_95_quantile&#39;] + 1)
  56. df[&#39;Y_max_log&#39;] = np.log(df[&#39;Y_max&#39;])
  57. df[&#39;X_mad_log&#39;] = np.log(df[&#39;X_mad&#39;])
  58. def calc_rise_log(x):
  59. idx_max = np.argmax(x)
  60. val_max = x[idx_max]
  61. rise = np.log(val_max) - np.log(abs(np.min(x[:idx_max + 1])) + 1) # max change before peak
  62. return rise
  63. def calc_fall_log(x):
  64. idx_max = np.argmax(x)
  65. val_max = x[idx_max]
  66. fall = np.log(val_max) - np.log(abs(np.min(x[idx_max:])) + 1) # drop after peak
  67. return fall
  68. df[&#39;rise_log&#39;] = np.array([calc_rise_log(df.iloc[i].X) for i in range(len(df))])
  69. df[&#39;fall_log&#39;] = np.array([calc_fall_log(df.iloc[i].X) for i in range(len(df))])
  70. num = 3
  71. df[&#39;rise_local_3_log&#39;] = df.apply(lambda row:
  72. calc_rise_log(np.array(row[&#39;X&#39;][max(0, row[&#39;X_peak_idx&#39;] - num):
  73. row[&#39;X_peak_idx&#39;] + num + 1])),
  74. axis=1)
  75. df[&#39;fall_local_3_log&#39;] = df.apply(lambda row:
  76. calc_fall_log(np.array(row[&#39;X&#39;][max(0, row[&#39;X_peak_idx&#39;] - num):
  77. row[&#39;X_peak_idx&#39;] + num + 1])),
  78. axis=1)
  79. num2 = 11
  80. df[&#39;rise_local_11_log&#39;] = df.apply(lambda row:
  81. calc_rise_log(np.array(row[&#39;X&#39;][max(0, row[&#39;X_peak_idx&#39;] - num2):
  82. row[&#39;X_peak_idx&#39;] + num2 + 1])),
  83. axis=1)
  84. df[&#39;fall_local_11_log&#39;] = df.apply(lambda row:
  85. calc_fall_log(np.array(row[&#39;X&#39;][max(0, row[&#39;X_peak_idx&#39;] - num2):
  86. row[&#39;X_peak_idx&#39;] + num2 + 1])),
  87. axis=1)
  88. return df
  89. def train_reg(df,
  90. feat_names,
  91. model_type=&#39;rf&#39;,
  92. outcome_def=&#39;Y_max_log&#39;,
  93. out_name=&#39;results/regression/test.pkl&#39;,
  94. seed=42,
  95. **kwargs):
  96. &#39;&#39;&#39;
  97. train regression model
  98. hyperparameters of model can be specified using **kwargs
  99. &#39;&#39;&#39;
  100. np.random.seed(seed)
  101. X = df[feat_names]
  102. # X = (X - X.mean()) / X.std() # normalize the data
  103. y = df[outcome_def].values
  104. if model_type == &#39;rf&#39;:
  105. m = RandomForestRegressor(n_estimators=100)
  106. elif model_type == &#39;dt&#39;:
  107. m = DecisionTreeRegressor()
  108. elif model_type == &#39;linear&#39;:
  109. m = LinearRegression()
  110. elif model_type == &#39;ridge&#39;:
  111. m = RidgeCV()
  112. elif model_type == &#39;svm&#39;:
  113. m = SVR(gamma=&#39;scale&#39;)
  114. elif model_type == &#39;gb&#39;:
  115. m = GradientBoostingRegressor()
  116. elif model_type == &#39;irf&#39;:
  117. m = irf.ensemble.wrf()
  118. elif &#39;nn&#39; in model_type: # neural nets
  119. &#34;&#34;&#34;
  120. train fully connected neural network
  121. &#34;&#34;&#34;
  122. H = kwargs[&#39;fcnn_hidden_neurons&#39;] if &#39;fcnn_hidden_neurons&#39; in kwargs else 40
  123. epochs = kwargs[&#39;fcnn_epochs&#39;] if &#39;fcnn_epochs&#39; in kwargs else 1000
  124. batch_size = kwargs[&#39;fcnn_batch_size&#39;] if &#39;fcnn_batch_size&#39; in kwargs else 1000
  125. track_name = kwargs[&#39;track_name&#39;] if &#39;track_name&#39; in kwargs else &#39;X_same_length&#39;
  126. D_in = len(df[track_name].iloc[0])
  127. m = neural_net_sklearn(D_in=D_in,
  128. H=H,
  129. p=len(feat_names)-1,
  130. epochs=epochs,
  131. batch_size=batch_size,
  132. track_name=track_name,
  133. arch=model_type)
  134. # scores_cv = {s: [] for s in scorers.keys()}
  135. # scores_test = {s: [] for s in scorers.keys()}
  136. imps = {&#39;model&#39;: [], &#39;imps&#39;: []}
  137. cell_nums_train = np.array(list(set(df.cell_num.values)))
  138. kf = KFold(n_splits=len(cell_nums_train))
  139. # split testing data based on cell num
  140. #idxs_test = df.cell_num.isin(cell_nums_test)
  141. #idxs_train = df.cell_num.isin(cell_nums_train)
  142. #X_test, Y_test = X[idxs_test], y[idxs_test]
  143. num_pts_by_fold_cv = []
  144. y_preds = {}
  145. cv_score = []
  146. cv_pearsonr = []
  147. print(&#34;Looping over cv...&#34;)
  148. # loops over cv, where test set order is cell_nums_train[0], ..., cell_nums_train[-1]
  149. for cv_idx, cv_val_idx in tqdm(kf.split(cell_nums_train)):
  150. # get sample indices
  151. idxs_cv = df.cell_num.isin(cell_nums_train[np.array(cv_idx)])
  152. idxs_val_cv = df.cell_num.isin(cell_nums_train[np.array(cv_val_idx)])
  153. X_train_cv, Y_train_cv = X[idxs_cv], y[idxs_cv]
  154. X_val_cv, Y_val_cv = X[idxs_val_cv], y[idxs_val_cv]
  155. num_pts_by_fold_cv.append(X_val_cv.shape[0])
  156. # resample training data
  157. # fit
  158. m.fit(X_train_cv, Y_train_cv)
  159. # get preds
  160. preds = m.predict(X_val_cv)
  161. y_preds[cell_nums_train[np.array(cv_val_idx)][0]] = preds
  162. if &#39;log&#39; in outcome_def:
  163. cv_score.append(r2_score(np.exp(Y_val_cv), np.exp(preds)))
  164. cv_pearsonr.append(pearsonr(np.exp(Y_val_cv), np.exp(preds))[0])
  165. else:
  166. print(r2_score(Y_val_cv, preds))
  167. cv_score.append(r2_score(Y_val_cv, preds))
  168. cv_pearsonr.append(pearsonr(Y_val_cv, preds)[0])
  169. print(&#34;Training with full data...&#34;)
  170. # cv_score = cv_score/len(cell_nums_train)
  171. m.fit(X, y)
  172. #print(cv_score)
  173. #test_preds = m.predict(X_test)
  174. results = {&#39;y_preds&#39;: y_preds,
  175. &#39;y&#39;: y,
  176. &#39;model_state_dict&#39;: m.model.state_dict(),
  177. #&#39;test_preds&#39;: test_preds,
  178. &#39;cv&#39;: {&#39;r2&#39;: cv_score, &#39;pearsonr&#39;: cv_pearsonr},
  179. &#39;model_type&#39;: model_type,
  180. #&#39;model&#39;: m,
  181. &#39;num_pts_by_fold_cv&#39;: np.array(num_pts_by_fold_cv),
  182. }
  183. if model_type in [&#39;rf&#39;, &#39;linear&#39;, &#39;ridge&#39;, &#39;gb&#39;, &#39;svm&#39;, &#39;irf&#39;]:
  184. results[&#39;model&#39;] = m
  185. # save results
  186. # os.makedirs(out_dir, exist_ok=True)
  187. pkl.dump(results, open(out_name, &#39;wb&#39;))
  188. def load_results(out_dir, by_cell=True):
  189. r = []
  190. for fname in os.listdir(out_dir):
  191. if os.path.isdir(oj(out_dir, fname)):
  192. continue
  193. d = pkl.load(open(oj(out_dir, fname), &#39;rb&#39;))
  194. metrics = {k: d[&#39;cv&#39;][k] for k in d[&#39;cv&#39;].keys() if not &#39;curve&#39; in k}
  195. num_pts_by_fold_cv = d[&#39;num_pts_by_fold_cv&#39;]
  196. print(metrics)
  197. out = {k: np.average(metrics[k], weights=num_pts_by_fold_cv) for k in metrics}
  198. if by_cell:
  199. out.update({&#39;cv_accuracy_by_cell&#39;: metrics[&#39;r2&#39;]})
  200. out.update({k + &#39;_std&#39;: np.std(metrics[k]) for k in metrics})
  201. out[&#39;model_type&#39;] = fname.replace(&#39;.pkl&#39;, &#39;&#39;) # d[&#39;model_type&#39;]
  202. print(d[&#39;cv&#39;].keys())
  203. # imp_mat = np.array(d[&#39;imps&#39;][&#39;imps&#39;])
  204. # imp_mu = imp_mat.mean(axis=0)
  205. # imp_sd = imp_mat.std(axis=0)
  206. # feat_names = d[&#39;feat_names_selected&#39;]
  207. # out.update({feat_names[i] + &#39;_f&#39;: imp_mu[i] for i in range(len(feat_names))})
  208. # out.update({feat_names[i]+&#39;_std_f&#39;: imp_sd[i] for i in range(len(feat_names))})
  209. r.append(pd.Series(out))
  210. r = pd.concat(r, axis=1, sort=False).T.infer_objects()
  211. r = r.reindex(sorted(r.columns), axis=1) # sort the column names
  212. r = r.round(3)
  213. r = r.set_index(&#39;model_type&#39;)
  214. return r
  215. def load_and_train(dset, outcome_def, out_dir, feat_names=None, use_processed=True):
  216. df = pd.read_pickle(f&#39;../data/tracks/tracks_{dset}.pkl&#39;)
  217. if dset == &#39;clath_aux_dynamin&#39;:
  218. df = df[df.catIdx.isin([1, 2])]
  219. df = df[df.lifetime &gt; 15]
  220. else:
  221. df = df[df[&#39;valid&#39;] == 1]
  222. df = features.add_basic_features(df)
  223. df = log_transforms(df)
  224. df = add_sig_mean(df)
  225. df_train = df[df.cell_num.isin(config.DSETS[dset][&#39;train&#39;])]
  226. df_test = df[df.cell_num.isin(config.DSETS[dset][&#39;test&#39;])]
  227. df_train = df_train.dropna()
  228. #outcome_def = &#39;Z_sig_mean&#39;
  229. #out_dir = &#39;results/regression/Sep15&#39;
  230. os.makedirs(out_dir, exist_ok=True)
  231. if not feat_names:
  232. feat_names = data.get_feature_names(df_train)
  233. feat_names = [x for x in feat_names
  234. if not x.startswith(&#39;sc_&#39;)
  235. and not x.startswith(&#39;nmf_&#39;)
  236. and not x in [&#39;center_max&#39;, &#39;left_max&#39;, &#39;right_max&#39;, &#39;up_max&#39;, &#39;down_max&#39;,
  237. &#39;X_max_around_Y_peak&#39;, &#39;X_max_after_Y_peak&#39;]
  238. and not x.startswith(&#39;pc_&#39;)
  239. and not &#39;log&#39; in x
  240. and not &#39;binary&#39; in x
  241. # and not &#39;slope&#39; in x
  242. ]
  243. for model_type in tqdm([&#39;linear&#39;, &#39;gb&#39;, &#39;rf&#39;, &#39;svm&#39;, &#39;ridge&#39;]):
  244. out_name = f&#39;{model_type}&#39;
  245. #print(out_name)
  246. if use_processed and os.path.exists(f&#39;{out_dir}/{out_name}.pkl&#39;):
  247. continue
  248. train_reg(df_train, feat_names=feat_names, model_type=model_type,
  249. outcome_def=outcome_def,
  250. out_name=f&#39;{out_dir}/{out_name}.pkl&#39;)
  251. def test_reg(df,
  252. model,
  253. feat_names=None,
  254. outcome_def=&#39;Y_max_log&#39;,
  255. out_name=&#39;results/regression/test.pkl&#39;,
  256. seed=42):
  257. np.random.seed(seed)
  258. if not feat_names:
  259. feat_names = data.get_feature_names(df)
  260. feat_names = [x for x in feat_names
  261. if not x.startswith(&#39;sc_&#39;)
  262. and not x.startswith(&#39;nmf_&#39;)
  263. and not x in [&#39;center_max&#39;, &#39;left_max&#39;, &#39;right_max&#39;, &#39;up_max&#39;, &#39;down_max&#39;,
  264. &#39;X_max_around_Y_peak&#39;, &#39;X_max_after_Y_peak&#39;]
  265. and not x.startswith(&#39;pc_&#39;)
  266. and not &#39;log&#39; in x
  267. and not &#39;binary&#39; in x
  268. # and not &#39;slope&#39; in x
  269. ]
  270. X = df[feat_names]
  271. # X = (X - X.mean()) / X.std() # normalize the data
  272. test_preds = model.predict(X)
  273. results = {&#39;preds&#39;: test_preds}
  274. if outcome_def in df.keys():
  275. y = df[outcome_def].values
  276. results[&#39;r2&#39;] = r2_score(y, test_preds)
  277. results[&#39;pearsonr&#39;] = pearsonr(y, test_preds)
  278. results[&#39;kendalltau&#39;] = kendalltau(y, test_preds)
  279. return results</code></pre>
  280. </details>
  281. </section>
  282. <section>
  283. </section>
  284. <section>
  285. </section>
  286. <section>
  287. <h2 class="section-title" id="header-functions">Functions</h2>
  288. <dl>
  289. <dt id="src.train_reg.add_robust_features"><code class="name flex">
  290. <span>def <span class="ident">add_robust_features</span></span>(<span>df)</span>
  291. </code></dt>
  292. <dd>
  293. <section class="desc"></section>
  294. <details class="source">
  295. <summary>
  296. <span>Expand source code</span>
  297. </summary>
  298. <pre><code class="python">def add_robust_features(df):
  299. df[&#39;X_95_quantile&#39;] = np.array([np.quantile(df.iloc[i].X, 0.95) for i in range(len(df))])
  300. df[&#39;X_mad&#39;] = np.array([robust.mad(df.iloc[i].X) for i in range(len(df))])
  301. return df</code></pre>
  302. </details>
  303. </dd>
  304. <dt id="src.train_reg.load_and_train"><code class="name flex">
  305. <span>def <span class="ident">load_and_train</span></span>(<span>dset, outcome_def, out_dir, feat_names=None, use_processed=True)</span>
  306. </code></dt>
  307. <dd>
  308. <section class="desc"></section>
  309. <details class="source">
  310. <summary>
  311. <span>Expand source code</span>
  312. </summary>
  313. <pre><code class="python">def load_and_train(dset, outcome_def, out_dir, feat_names=None, use_processed=True):
  314. df = pd.read_pickle(f&#39;../data/tracks/tracks_{dset}.pkl&#39;)
  315. if dset == &#39;clath_aux_dynamin&#39;:
  316. df = df[df.catIdx.isin([1, 2])]
  317. df = df[df.lifetime &gt; 15]
  318. else:
  319. df = df[df[&#39;valid&#39;] == 1]
  320. df = features.add_basic_features(df)
  321. df = log_transforms(df)
  322. df = add_sig_mean(df)
  323. df_train = df[df.cell_num.isin(config.DSETS[dset][&#39;train&#39;])]
  324. df_test = df[df.cell_num.isin(config.DSETS[dset][&#39;test&#39;])]
  325. df_train = df_train.dropna()
  326. #outcome_def = &#39;Z_sig_mean&#39;
  327. #out_dir = &#39;results/regression/Sep15&#39;
  328. os.makedirs(out_dir, exist_ok=True)
  329. if not feat_names:
  330. feat_names = data.get_feature_names(df_train)
  331. feat_names = [x for x in feat_names
  332. if not x.startswith(&#39;sc_&#39;)
  333. and not x.startswith(&#39;nmf_&#39;)
  334. and not x in [&#39;center_max&#39;, &#39;left_max&#39;, &#39;right_max&#39;, &#39;up_max&#39;, &#39;down_max&#39;,
  335. &#39;X_max_around_Y_peak&#39;, &#39;X_max_after_Y_peak&#39;]
  336. and not x.startswith(&#39;pc_&#39;)
  337. and not &#39;log&#39; in x
  338. and not &#39;binary&#39; in x
  339. # and not &#39;slope&#39; in x
  340. ]
  341. for model_type in tqdm([&#39;linear&#39;, &#39;gb&#39;, &#39;rf&#39;, &#39;svm&#39;, &#39;ridge&#39;]):
  342. out_name = f&#39;{model_type}&#39;
  343. #print(out_name)
  344. if use_processed and os.path.exists(f&#39;{out_dir}/{out_name}.pkl&#39;):
  345. continue
  346. train_reg(df_train, feat_names=feat_names, model_type=model_type,
  347. outcome_def=outcome_def,
  348. out_name=f&#39;{out_dir}/{out_name}.pkl&#39;) </code></pre>
  349. </details>
  350. </dd>
  351. <dt id="src.train_reg.load_results"><code class="name flex">
  352. <span>def <span class="ident">load_results</span></span>(<span>out_dir, by_cell=True)</span>
  353. </code></dt>
  354. <dd>
  355. <section class="desc"></section>
  356. <details class="source">
  357. <summary>
  358. <span>Expand source code</span>
  359. </summary>
  360. <pre><code class="python">def load_results(out_dir, by_cell=True):
  361. r = []
  362. for fname in os.listdir(out_dir):
  363. if os.path.isdir(oj(out_dir, fname)):
  364. continue
  365. d = pkl.load(open(oj(out_dir, fname), &#39;rb&#39;))
  366. metrics = {k: d[&#39;cv&#39;][k] for k in d[&#39;cv&#39;].keys() if not &#39;curve&#39; in k}
  367. num_pts_by_fold_cv = d[&#39;num_pts_by_fold_cv&#39;]
  368. print(metrics)
  369. out = {k: np.average(metrics[k], weights=num_pts_by_fold_cv) for k in metrics}
  370. if by_cell:
  371. out.update({&#39;cv_accuracy_by_cell&#39;: metrics[&#39;r2&#39;]})
  372. out.update({k + &#39;_std&#39;: np.std(metrics[k]) for k in metrics})
  373. out[&#39;model_type&#39;] = fname.replace(&#39;.pkl&#39;, &#39;&#39;) # d[&#39;model_type&#39;]
  374. print(d[&#39;cv&#39;].keys())
  375. # imp_mat = np.array(d[&#39;imps&#39;][&#39;imps&#39;])
  376. # imp_mu = imp_mat.mean(axis=0)
  377. # imp_sd = imp_mat.std(axis=0)
  378. # feat_names = d[&#39;feat_names_selected&#39;]
  379. # out.update({feat_names[i] + &#39;_f&#39;: imp_mu[i] for i in range(len(feat_names))})
  380. # out.update({feat_names[i]+&#39;_std_f&#39;: imp_sd[i] for i in range(len(feat_names))})
  381. r.append(pd.Series(out))
  382. r = pd.concat(r, axis=1, sort=False).T.infer_objects()
  383. r = r.reindex(sorted(r.columns), axis=1) # sort the column names
  384. r = r.round(3)
  385. r = r.set_index(&#39;model_type&#39;)
  386. return r</code></pre>
  387. </details>
  388. </dd>
  389. <dt id="src.train_reg.log_transforms"><code class="name flex">
  390. <span>def <span class="ident">log_transforms</span></span>(<span>df)</span>
  391. </code></dt>
  392. <dd>
  393. <section class="desc"></section>
  394. <details class="source">
  395. <summary>
  396. <span>Expand source code</span>
  397. </summary>
  398. <pre><code class="python">def log_transforms(df):
  399. df = add_robust_features(df)
  400. df[&#39;X_max_log&#39;] = np.log(df[&#39;X_max&#39;])
  401. df[&#39;X_95_quantile_log&#39;] = np.log(df[&#39;X_95_quantile&#39;] + 1)
  402. df[&#39;Y_max_log&#39;] = np.log(df[&#39;Y_max&#39;])
  403. df[&#39;X_mad_log&#39;] = np.log(df[&#39;X_mad&#39;])
  404. def calc_rise_log(x):
  405. idx_max = np.argmax(x)
  406. val_max = x[idx_max]
  407. rise = np.log(val_max) - np.log(abs(np.min(x[:idx_max + 1])) + 1) # max change before peak
  408. return rise
  409. def calc_fall_log(x):
  410. idx_max = np.argmax(x)
  411. val_max = x[idx_max]
  412. fall = np.log(val_max) - np.log(abs(np.min(x[idx_max:])) + 1) # drop after peak
  413. return fall
  414. df[&#39;rise_log&#39;] = np.array([calc_rise_log(df.iloc[i].X) for i in range(len(df))])
  415. df[&#39;fall_log&#39;] = np.array([calc_fall_log(df.iloc[i].X) for i in range(len(df))])
  416. num = 3
  417. df[&#39;rise_local_3_log&#39;] = df.apply(lambda row:
  418. calc_rise_log(np.array(row[&#39;X&#39;][max(0, row[&#39;X_peak_idx&#39;] - num):
  419. row[&#39;X_peak_idx&#39;] + num + 1])),
  420. axis=1)
  421. df[&#39;fall_local_3_log&#39;] = df.apply(lambda row:
  422. calc_fall_log(np.array(row[&#39;X&#39;][max(0, row[&#39;X_peak_idx&#39;] - num):
  423. row[&#39;X_peak_idx&#39;] + num + 1])),
  424. axis=1)
  425. num2 = 11
  426. df[&#39;rise_local_11_log&#39;] = df.apply(lambda row:
  427. calc_rise_log(np.array(row[&#39;X&#39;][max(0, row[&#39;X_peak_idx&#39;] - num2):
  428. row[&#39;X_peak_idx&#39;] + num2 + 1])),
  429. axis=1)
  430. df[&#39;fall_local_11_log&#39;] = df.apply(lambda row:
  431. calc_fall_log(np.array(row[&#39;X&#39;][max(0, row[&#39;X_peak_idx&#39;] - num2):
  432. row[&#39;X_peak_idx&#39;] + num2 + 1])),
  433. axis=1)
  434. return df</code></pre>
  435. </details>
  436. </dd>
  437. <dt id="src.train_reg.test_reg"><code class="name flex">
  438. <span>def <span class="ident">test_reg</span></span>(<span>df, model, feat_names=None, outcome_def='Y_max_log', out_name='results/regression/test.pkl', seed=42)</span>
  439. </code></dt>
  440. <dd>
  441. <section class="desc"></section>
  442. <details class="source">
  443. <summary>
  444. <span>Expand source code</span>
  445. </summary>
  446. <pre><code class="python">def test_reg(df,
  447. model,
  448. feat_names=None,
  449. outcome_def=&#39;Y_max_log&#39;,
  450. out_name=&#39;results/regression/test.pkl&#39;,
  451. seed=42):
  452. np.random.seed(seed)
  453. if not feat_names:
  454. feat_names = data.get_feature_names(df)
  455. feat_names = [x for x in feat_names
  456. if not x.startswith(&#39;sc_&#39;)
  457. and not x.startswith(&#39;nmf_&#39;)
  458. and not x in [&#39;center_max&#39;, &#39;left_max&#39;, &#39;right_max&#39;, &#39;up_max&#39;, &#39;down_max&#39;,
  459. &#39;X_max_around_Y_peak&#39;, &#39;X_max_after_Y_peak&#39;]
  460. and not x.startswith(&#39;pc_&#39;)
  461. and not &#39;log&#39; in x
  462. and not &#39;binary&#39; in x
  463. # and not &#39;slope&#39; in x
  464. ]
  465. X = df[feat_names]
  466. # X = (X - X.mean()) / X.std() # normalize the data
  467. test_preds = model.predict(X)
  468. results = {&#39;preds&#39;: test_preds}
  469. if outcome_def in df.keys():
  470. y = df[outcome_def].values
  471. results[&#39;r2&#39;] = r2_score(y, test_preds)
  472. results[&#39;pearsonr&#39;] = pearsonr(y, test_preds)
  473. results[&#39;kendalltau&#39;] = kendalltau(y, test_preds)
  474. return results</code></pre>
  475. </details>
  476. </dd>
  477. <dt id="src.train_reg.train_reg"><code class="name flex">
  478. <span>def <span class="ident">train_reg</span></span>(<span>df, feat_names, model_type='rf', outcome_def='Y_max_log', out_name='results/regression/test.pkl', seed=42, **kwargs)</span>
  479. </code></dt>
  480. <dd>
  481. <section class="desc"><p>train regression model</p>
  482. <p>hyperparameters of model can be specified using **kwargs</p></section>
  483. <details class="source">
  484. <summary>
  485. <span>Expand source code</span>
  486. </summary>
  487. <pre><code class="python">def train_reg(df,
  488. feat_names,
  489. model_type=&#39;rf&#39;,
  490. outcome_def=&#39;Y_max_log&#39;,
  491. out_name=&#39;results/regression/test.pkl&#39;,
  492. seed=42,
  493. **kwargs):
  494. &#39;&#39;&#39;
  495. train regression model
  496. hyperparameters of model can be specified using **kwargs
  497. &#39;&#39;&#39;
  498. np.random.seed(seed)
  499. X = df[feat_names]
  500. # X = (X - X.mean()) / X.std() # normalize the data
  501. y = df[outcome_def].values
  502. if model_type == &#39;rf&#39;:
  503. m = RandomForestRegressor(n_estimators=100)
  504. elif model_type == &#39;dt&#39;:
  505. m = DecisionTreeRegressor()
  506. elif model_type == &#39;linear&#39;:
  507. m = LinearRegression()
  508. elif model_type == &#39;ridge&#39;:
  509. m = RidgeCV()
  510. elif model_type == &#39;svm&#39;:
  511. m = SVR(gamma=&#39;scale&#39;)
  512. elif model_type == &#39;gb&#39;:
  513. m = GradientBoostingRegressor()
  514. elif model_type == &#39;irf&#39;:
  515. m = irf.ensemble.wrf()
  516. elif &#39;nn&#39; in model_type: # neural nets
  517. &#34;&#34;&#34;
  518. train fully connected neural network
  519. &#34;&#34;&#34;
  520. H = kwargs[&#39;fcnn_hidden_neurons&#39;] if &#39;fcnn_hidden_neurons&#39; in kwargs else 40
  521. epochs = kwargs[&#39;fcnn_epochs&#39;] if &#39;fcnn_epochs&#39; in kwargs else 1000
  522. batch_size = kwargs[&#39;fcnn_batch_size&#39;] if &#39;fcnn_batch_size&#39; in kwargs else 1000
  523. track_name = kwargs[&#39;track_name&#39;] if &#39;track_name&#39; in kwargs else &#39;X_same_length&#39;
  524. D_in = len(df[track_name].iloc[0])
  525. m = neural_net_sklearn(D_in=D_in,
  526. H=H,
  527. p=len(feat_names)-1,
  528. epochs=epochs,
  529. batch_size=batch_size,
  530. track_name=track_name,
  531. arch=model_type)
  532. # scores_cv = {s: [] for s in scorers.keys()}
  533. # scores_test = {s: [] for s in scorers.keys()}
  534. imps = {&#39;model&#39;: [], &#39;imps&#39;: []}
  535. cell_nums_train = np.array(list(set(df.cell_num.values)))
  536. kf = KFold(n_splits=len(cell_nums_train))
  537. # split testing data based on cell num
  538. #idxs_test = df.cell_num.isin(cell_nums_test)
  539. #idxs_train = df.cell_num.isin(cell_nums_train)
  540. #X_test, Y_test = X[idxs_test], y[idxs_test]
  541. num_pts_by_fold_cv = []
  542. y_preds = {}
  543. cv_score = []
  544. cv_pearsonr = []
  545. print(&#34;Looping over cv...&#34;)
  546. # loops over cv, where test set order is cell_nums_train[0], ..., cell_nums_train[-1]
  547. for cv_idx, cv_val_idx in tqdm(kf.split(cell_nums_train)):
  548. # get sample indices
  549. idxs_cv = df.cell_num.isin(cell_nums_train[np.array(cv_idx)])
  550. idxs_val_cv = df.cell_num.isin(cell_nums_train[np.array(cv_val_idx)])
  551. X_train_cv, Y_train_cv = X[idxs_cv], y[idxs_cv]
  552. X_val_cv, Y_val_cv = X[idxs_val_cv], y[idxs_val_cv]
  553. num_pts_by_fold_cv.append(X_val_cv.shape[0])
  554. # resample training data
  555. # fit
  556. m.fit(X_train_cv, Y_train_cv)
  557. # get preds
  558. preds = m.predict(X_val_cv)
  559. y_preds[cell_nums_train[np.array(cv_val_idx)][0]] = preds
  560. if &#39;log&#39; in outcome_def:
  561. cv_score.append(r2_score(np.exp(Y_val_cv), np.exp(preds)))
  562. cv_pearsonr.append(pearsonr(np.exp(Y_val_cv), np.exp(preds))[0])
  563. else:
  564. print(r2_score(Y_val_cv, preds))
  565. cv_score.append(r2_score(Y_val_cv, preds))
  566. cv_pearsonr.append(pearsonr(Y_val_cv, preds)[0])
  567. print(&#34;Training with full data...&#34;)
  568. # cv_score = cv_score/len(cell_nums_train)
  569. m.fit(X, y)
  570. #print(cv_score)
  571. #test_preds = m.predict(X_test)
  572. results = {&#39;y_preds&#39;: y_preds,
  573. &#39;y&#39;: y,
  574. &#39;model_state_dict&#39;: m.model.state_dict(),
  575. #&#39;test_preds&#39;: test_preds,
  576. &#39;cv&#39;: {&#39;r2&#39;: cv_score, &#39;pearsonr&#39;: cv_pearsonr},
  577. &#39;model_type&#39;: model_type,
  578. #&#39;model&#39;: m,
  579. &#39;num_pts_by_fold_cv&#39;: np.array(num_pts_by_fold_cv),
  580. }
  581. if model_type in [&#39;rf&#39;, &#39;linear&#39;, &#39;ridge&#39;, &#39;gb&#39;, &#39;svm&#39;, &#39;irf&#39;]:
  582. results[&#39;model&#39;] = m
  583. # save results
  584. # os.makedirs(out_dir, exist_ok=True)
  585. pkl.dump(results, open(out_name, &#39;wb&#39;))</code></pre>
  586. </details>
  587. </dd>
  588. </dl>
  589. </section>
  590. <section>
  591. </section>
  592. </article>
  593. <nav id="sidebar">
  594. <h1>Index</h1>
  595. <div class="toc">
  596. <ul></ul>
  597. </div>
  598. <ul id="index">
  599. <li><h3>Super-module</h3>
  600. <ul>
  601. <li><code><a title="src" href="index.html">src</a></code></li>
  602. </ul>
  603. </li>
  604. <li><h3><a href="#header-functions">Functions</a></h3>
  605. <ul class="two-column">
  606. <li><code><a title="src.train_reg.add_robust_features" href="#src.train_reg.add_robust_features">add_robust_features</a></code></li>
  607. <li><code><a title="src.train_reg.load_and_train" href="#src.train_reg.load_and_train">load_and_train</a></code></li>
  608. <li><code><a title="src.train_reg.load_results" href="#src.train_reg.load_results">load_results</a></code></li>
  609. <li><code><a title="src.train_reg.log_transforms" href="#src.train_reg.log_transforms">log_transforms</a></code></li>
  610. <li><code><a title="src.train_reg.test_reg" href="#src.train_reg.test_reg">test_reg</a></code></li>
  611. <li><code><a title="src.train_reg.train_reg" href="#src.train_reg.train_reg">train_reg</a></code></li>
  612. </ul>
  613. </li>
  614. </ul>
  615. </nav>
  616. </main>
  617. <footer id="footer">
  618. <p>Generated by <a href="https://pdoc3.github.io/pdoc"><cite>pdoc</cite> 0.7.2</a>.</p>
  619. </footer>
  620. <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
  621. <script>hljs.initHighlightingOnLoad()</script>
  622. </body>
  623. </html>
Tip!

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

Comments

Loading...