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.html 22 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
  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 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</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 sys
  28. from sklearn.linear_model import LogisticRegression, Lasso
  29. from sklearn.neural_network import MLPClassifier
  30. from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, VotingClassifier
  31. from sklearn.tree import DecisionTreeClassifier
  32. from sklearn.svm import SVC
  33. from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis as QDA
  34. import eli5
  35. import numpy as np
  36. from copy import deepcopy
  37. from sklearn import metrics
  38. from sklearn.feature_selection import SelectFromModel
  39. from sklearn.calibration import CalibratedClassifierCV
  40. from imblearn.over_sampling import RandomOverSampler, SMOTE
  41. from sklearn.model_selection import KFold
  42. import pickle as pkl
  43. sys.path.append(&#39;lib&#39;)
  44. from sklearn.neighbors import KNeighborsClassifier as KNN
  45. scorers = {&#39;balanced_accuracy&#39;: metrics.balanced_accuracy_score, &#39;accuracy&#39;: metrics.accuracy_score,
  46. &#39;precision&#39;: metrics.precision_score, &#39;recall&#39;: metrics.recall_score, &#39;f1&#39;: metrics.f1_score,
  47. &#39;roc_auc&#39;: metrics.roc_auc_score,
  48. &#39;precision_recall_curve&#39;: metrics.precision_recall_curve, &#39;roc_curve&#39;: metrics.roc_curve}
  49. def get_feature_importance(model, model_type, X_val, Y_val):
  50. if &#39;Calibrated&#39; in str(type(model)):
  51. perm = eli5.sklearn.permutation_importance.PermutationImportance(model).fit(X_val, Y_val)
  52. imps = perm.feature_importances_
  53. elif model_type in [&#39;dt&#39;]:
  54. imps = model.feature_importances_
  55. elif model_type in [&#39;rf&#39;, &#39;irf&#39;]:
  56. # imps, _ = feature_importance(model, np.array(X_val), np.transpose(np.vstack((Y_val, 1-Y_val))))
  57. imps = model.feature_importances_
  58. elif model_type == &#39;logistic&#39;:
  59. imps = model.coef_
  60. else:
  61. perm = eli5.sklearn.permutation_importance.PermutationImportance(model).fit(X_val, Y_val)
  62. imps = perm.feature_importances_
  63. return imps.squeeze()
  64. def balance(X, y, balancing=&#39;ros&#39;, balancing_ratio=1):
  65. &#39;&#39;&#39;Balance classes in y using strategy specified by balancing
  66. Params
  67. -----
  68. balancing_ratio: float
  69. ratio of pos: neg samples
  70. &#39;&#39;&#39;
  71. class0 = np.sum(y == 0)
  72. class1 = np.sum(y == 1)
  73. class_max = max(class0, class1)
  74. if balancing_ratio &gt;= 1:
  75. sample_nums = {0: int(class_max), 1: int(class_max * balancing_ratio)}
  76. else:
  77. sample_nums = {0: int(class_max / balancing_ratio), 1: int(class_max)}
  78. if balancing == &#39;none&#39;:
  79. return X, y
  80. if balancing == &#39;ros&#39;:
  81. sampler = RandomOverSampler(sampling_strategy=sample_nums, random_state=42)
  82. elif balancing == &#39;smote&#39;:
  83. sampler = SMOTE(sampling_strategy=sample_nums, random_state=42)
  84. X_r, Y_r = sampler.fit_resample(X, y)
  85. return X_r, Y_r
  86. def train(df, feat_names,
  87. cell_nums_feature_selection, cell_nums_train,
  88. model_type=&#39;rf&#39;, outcome_def=&#39;y_thresh&#39;,
  89. balancing=&#39;ros&#39;, balancing_ratio=1, out_name=&#39;results/classify/test.pkl&#39;,
  90. calibrated=False, feature_selection=None,
  91. feature_selection_num=3, hyperparam=0, seed=42):
  92. &#39;&#39;&#39;Run training and fit models
  93. This will balance the data
  94. This will normalize the features before fitting
  95. Params
  96. ------
  97. normalize: bool
  98. if True, will normalize features before fitting
  99. cell_nums_feature_selection: list[str]
  100. cell names to use for feature selection
  101. &#39;&#39;&#39;
  102. np.random.seed(seed)
  103. X = df[feat_names]
  104. X = (X - X.mean()) / X.std() # normalize the data
  105. y = df[outcome_def].values
  106. if model_type == &#39;rf&#39;:
  107. m = RandomForestClassifier(n_estimators=100)
  108. elif model_type == &#39;dt&#39;:
  109. m = DecisionTreeClassifier()
  110. elif model_type == &#39;logistic&#39;:
  111. m = LogisticRegression(solver=&#39;lbfgs&#39;)
  112. elif model_type == &#39;svm&#39;:
  113. h = {
  114. -1: 0.5,
  115. 0: 1,
  116. 1: 5
  117. }[hyperparam]
  118. m = SVC(C=h, gamma=&#39;scale&#39;)
  119. elif model_type == &#39;mlp2&#39;:
  120. h = {
  121. -1: (50,),
  122. 0: (100,),
  123. 1: (50, 50,)
  124. }[hyperparam]
  125. m = MLPClassifier(hidden_layer_sizes=h)
  126. elif model_type == &#39;gb&#39;:
  127. m = GradientBoostingClassifier()
  128. elif model_type == &#39;qda&#39;:
  129. m = QDA()
  130. elif model_type == &#39;KNN&#39;:
  131. m = KNN()
  132. elif model_type == &#39;irf&#39;:
  133. import irf
  134. m = irf.ensemble.wrf()
  135. elif model_type == &#39;voting_mlp+svm+rf&#39;:
  136. models_list = [(&#39;mlp&#39;, MLPClassifier()),
  137. (&#39;svm&#39;, SVC(gamma=&#39;scale&#39;)),
  138. (&#39;rf&#39;, RandomForestClassifier(n_estimators=100))]
  139. m = VotingClassifier(estimators=models_list, voting=&#39;hard&#39;)
  140. if calibrated:
  141. m = CalibratedClassifierCV(m)
  142. scores_cv = {s: [] for s in scorers.keys()}
  143. imps = {&#39;model&#39;: [], &#39;imps&#39;: []}
  144. kf = KFold(n_splits=len(cell_nums_train))
  145. # feature selection on cell num 1
  146. feature_selector = None
  147. if feature_selection is not None:
  148. if feature_selection == &#39;select_lasso&#39;:
  149. feature_selector_model = Lasso()
  150. elif feature_selection == &#39;select_rf&#39;:
  151. feature_selector_model = RandomForestClassifier()
  152. # select only feature_selection_num features
  153. feature_selector = SelectFromModel(feature_selector_model, threshold=-np.inf,
  154. max_features=feature_selection_num)
  155. idxs = df.cell_num.isin(cell_nums_feature_selection)
  156. feature_selector.fit(X[idxs], y[idxs].reshape(-1, 1))
  157. X = feature_selector.transform(X)
  158. support = np.array(feature_selector.get_support())
  159. else:
  160. support = np.ones(len(feat_names)).astype(np.bool)
  161. num_pts_by_fold_cv = []
  162. # loops over cv, where validation set order is cell_nums_train[0], ..., cell_nums_train[-1]
  163. for cv_idx, cv_val_idx in kf.split(cell_nums_train):
  164. # get sample indices
  165. idxs_cv = df.cell_num.isin(cell_nums_train[np.array(cv_idx)])
  166. idxs_val_cv = df.cell_num.isin(cell_nums_train[np.array(cv_val_idx)])
  167. X_train_cv, Y_train_cv = X[idxs_cv], y[idxs_cv]
  168. X_val_cv, Y_val_cv = X[idxs_val_cv], y[idxs_val_cv]
  169. num_pts_by_fold_cv.append(X_val_cv.shape[0])
  170. # resample training data
  171. X_train_r_cv, Y_train_r_cv = balance(X_train_cv, Y_train_cv, balancing, balancing_ratio)
  172. # fit
  173. m.fit(X_train_r_cv, Y_train_r_cv)
  174. # get preds
  175. preds = m.predict(X_val_cv)
  176. if &#39;svm&#39; in model_type:
  177. preds_proba = preds
  178. else:
  179. preds_proba = m.predict_proba(X_val_cv)[:, 1]
  180. # add scores
  181. for s in scorers.keys():
  182. scorer = scorers[s]
  183. if &#39;roc&#39; in s or &#39;curve&#39; in s:
  184. scores_cv[s].append(scorer(Y_val_cv, preds_proba))
  185. else:
  186. scores_cv[s].append(scorer(Y_val_cv, preds))
  187. imps[&#39;model&#39;].append(deepcopy(m))
  188. imps[&#39;imps&#39;].append(get_feature_importance(m, model_type, X_val_cv, Y_val_cv))
  189. # save results
  190. # os.makedirs(out_dir, exist_ok=True)
  191. results = {&#39;metrics&#39;: list(scorers.keys()),
  192. &#39;num_pts_by_fold_cv&#39;: np.array(num_pts_by_fold_cv),
  193. &#39;cv&#39;: scores_cv,
  194. &#39;imps&#39;: imps, # note this contains the model
  195. &#39;feat_names&#39;: feat_names,
  196. &#39;feature_selector&#39;: feature_selector,
  197. &#39;feature_selection_num&#39;: feature_selection_num,
  198. &#39;model_type&#39;: model_type,
  199. &#39;balancing&#39;: balancing,
  200. &#39;feat_names_selected&#39;: np.array(feat_names)[support],
  201. &#39;calibrated&#39;: calibrated
  202. }
  203. pkl.dump(results, open(out_name, &#39;wb&#39;))</code></pre>
  204. </details>
  205. </section>
  206. <section>
  207. </section>
  208. <section>
  209. </section>
  210. <section>
  211. <h2 class="section-title" id="header-functions">Functions</h2>
  212. <dl>
  213. <dt id="src.train.balance"><code class="name flex">
  214. <span>def <span class="ident">balance</span></span>(<span>X, y, balancing='ros', balancing_ratio=1)</span>
  215. </code></dt>
  216. <dd>
  217. <section class="desc"><p>Balance classes in y using strategy specified by balancing
  218. Params</p>
  219. <hr>
  220. <dl>
  221. <dt><strong><code>balancing_ratio</code></strong> :&ensp;<code>float</code></dt>
  222. <dd>ratio of pos: neg samples</dd>
  223. </dl></section>
  224. <details class="source">
  225. <summary>
  226. <span>Expand source code</span>
  227. </summary>
  228. <pre><code class="python">def balance(X, y, balancing=&#39;ros&#39;, balancing_ratio=1):
  229. &#39;&#39;&#39;Balance classes in y using strategy specified by balancing
  230. Params
  231. -----
  232. balancing_ratio: float
  233. ratio of pos: neg samples
  234. &#39;&#39;&#39;
  235. class0 = np.sum(y == 0)
  236. class1 = np.sum(y == 1)
  237. class_max = max(class0, class1)
  238. if balancing_ratio &gt;= 1:
  239. sample_nums = {0: int(class_max), 1: int(class_max * balancing_ratio)}
  240. else:
  241. sample_nums = {0: int(class_max / balancing_ratio), 1: int(class_max)}
  242. if balancing == &#39;none&#39;:
  243. return X, y
  244. if balancing == &#39;ros&#39;:
  245. sampler = RandomOverSampler(sampling_strategy=sample_nums, random_state=42)
  246. elif balancing == &#39;smote&#39;:
  247. sampler = SMOTE(sampling_strategy=sample_nums, random_state=42)
  248. X_r, Y_r = sampler.fit_resample(X, y)
  249. return X_r, Y_r</code></pre>
  250. </details>
  251. </dd>
  252. <dt id="src.train.get_feature_importance"><code class="name flex">
  253. <span>def <span class="ident">get_feature_importance</span></span>(<span>model, model_type, X_val, Y_val)</span>
  254. </code></dt>
  255. <dd>
  256. <section class="desc"></section>
  257. <details class="source">
  258. <summary>
  259. <span>Expand source code</span>
  260. </summary>
  261. <pre><code class="python">def get_feature_importance(model, model_type, X_val, Y_val):
  262. if &#39;Calibrated&#39; in str(type(model)):
  263. perm = eli5.sklearn.permutation_importance.PermutationImportance(model).fit(X_val, Y_val)
  264. imps = perm.feature_importances_
  265. elif model_type in [&#39;dt&#39;]:
  266. imps = model.feature_importances_
  267. elif model_type in [&#39;rf&#39;, &#39;irf&#39;]:
  268. # imps, _ = feature_importance(model, np.array(X_val), np.transpose(np.vstack((Y_val, 1-Y_val))))
  269. imps = model.feature_importances_
  270. elif model_type == &#39;logistic&#39;:
  271. imps = model.coef_
  272. else:
  273. perm = eli5.sklearn.permutation_importance.PermutationImportance(model).fit(X_val, Y_val)
  274. imps = perm.feature_importances_
  275. return imps.squeeze()</code></pre>
  276. </details>
  277. </dd>
  278. <dt id="src.train.train"><code class="name flex">
  279. <span>def <span class="ident">train</span></span>(<span>df, feat_names, cell_nums_feature_selection, cell_nums_train, model_type='rf', outcome_def='y_thresh', balancing='ros', balancing_ratio=1, out_name='results/classify/test.pkl', calibrated=False, feature_selection=None, feature_selection_num=3, hyperparam=0, seed=42)</span>
  280. </code></dt>
  281. <dd>
  282. <section class="desc"><p>Run training and fit models
  283. This will balance the data
  284. This will normalize the features before fitting</p>
  285. <h2 id="params">Params</h2>
  286. <dl>
  287. <dt><strong><code>normalize</code></strong> :&ensp;<code>bool</code></dt>
  288. <dd>if True, will normalize features before fitting</dd>
  289. <dt><strong><code>cell_nums_feature_selection</code></strong> :&ensp;<code>list</code>[<code>str</code>]</dt>
  290. <dd>cell names to use for feature selection</dd>
  291. </dl></section>
  292. <details class="source">
  293. <summary>
  294. <span>Expand source code</span>
  295. </summary>
  296. <pre><code class="python">def train(df, feat_names,
  297. cell_nums_feature_selection, cell_nums_train,
  298. model_type=&#39;rf&#39;, outcome_def=&#39;y_thresh&#39;,
  299. balancing=&#39;ros&#39;, balancing_ratio=1, out_name=&#39;results/classify/test.pkl&#39;,
  300. calibrated=False, feature_selection=None,
  301. feature_selection_num=3, hyperparam=0, seed=42):
  302. &#39;&#39;&#39;Run training and fit models
  303. This will balance the data
  304. This will normalize the features before fitting
  305. Params
  306. ------
  307. normalize: bool
  308. if True, will normalize features before fitting
  309. cell_nums_feature_selection: list[str]
  310. cell names to use for feature selection
  311. &#39;&#39;&#39;
  312. np.random.seed(seed)
  313. X = df[feat_names]
  314. X = (X - X.mean()) / X.std() # normalize the data
  315. y = df[outcome_def].values
  316. if model_type == &#39;rf&#39;:
  317. m = RandomForestClassifier(n_estimators=100)
  318. elif model_type == &#39;dt&#39;:
  319. m = DecisionTreeClassifier()
  320. elif model_type == &#39;logistic&#39;:
  321. m = LogisticRegression(solver=&#39;lbfgs&#39;)
  322. elif model_type == &#39;svm&#39;:
  323. h = {
  324. -1: 0.5,
  325. 0: 1,
  326. 1: 5
  327. }[hyperparam]
  328. m = SVC(C=h, gamma=&#39;scale&#39;)
  329. elif model_type == &#39;mlp2&#39;:
  330. h = {
  331. -1: (50,),
  332. 0: (100,),
  333. 1: (50, 50,)
  334. }[hyperparam]
  335. m = MLPClassifier(hidden_layer_sizes=h)
  336. elif model_type == &#39;gb&#39;:
  337. m = GradientBoostingClassifier()
  338. elif model_type == &#39;qda&#39;:
  339. m = QDA()
  340. elif model_type == &#39;KNN&#39;:
  341. m = KNN()
  342. elif model_type == &#39;irf&#39;:
  343. import irf
  344. m = irf.ensemble.wrf()
  345. elif model_type == &#39;voting_mlp+svm+rf&#39;:
  346. models_list = [(&#39;mlp&#39;, MLPClassifier()),
  347. (&#39;svm&#39;, SVC(gamma=&#39;scale&#39;)),
  348. (&#39;rf&#39;, RandomForestClassifier(n_estimators=100))]
  349. m = VotingClassifier(estimators=models_list, voting=&#39;hard&#39;)
  350. if calibrated:
  351. m = CalibratedClassifierCV(m)
  352. scores_cv = {s: [] for s in scorers.keys()}
  353. imps = {&#39;model&#39;: [], &#39;imps&#39;: []}
  354. kf = KFold(n_splits=len(cell_nums_train))
  355. # feature selection on cell num 1
  356. feature_selector = None
  357. if feature_selection is not None:
  358. if feature_selection == &#39;select_lasso&#39;:
  359. feature_selector_model = Lasso()
  360. elif feature_selection == &#39;select_rf&#39;:
  361. feature_selector_model = RandomForestClassifier()
  362. # select only feature_selection_num features
  363. feature_selector = SelectFromModel(feature_selector_model, threshold=-np.inf,
  364. max_features=feature_selection_num)
  365. idxs = df.cell_num.isin(cell_nums_feature_selection)
  366. feature_selector.fit(X[idxs], y[idxs].reshape(-1, 1))
  367. X = feature_selector.transform(X)
  368. support = np.array(feature_selector.get_support())
  369. else:
  370. support = np.ones(len(feat_names)).astype(np.bool)
  371. num_pts_by_fold_cv = []
  372. # loops over cv, where validation set order is cell_nums_train[0], ..., cell_nums_train[-1]
  373. for cv_idx, cv_val_idx in kf.split(cell_nums_train):
  374. # get sample indices
  375. idxs_cv = df.cell_num.isin(cell_nums_train[np.array(cv_idx)])
  376. idxs_val_cv = df.cell_num.isin(cell_nums_train[np.array(cv_val_idx)])
  377. X_train_cv, Y_train_cv = X[idxs_cv], y[idxs_cv]
  378. X_val_cv, Y_val_cv = X[idxs_val_cv], y[idxs_val_cv]
  379. num_pts_by_fold_cv.append(X_val_cv.shape[0])
  380. # resample training data
  381. X_train_r_cv, Y_train_r_cv = balance(X_train_cv, Y_train_cv, balancing, balancing_ratio)
  382. # fit
  383. m.fit(X_train_r_cv, Y_train_r_cv)
  384. # get preds
  385. preds = m.predict(X_val_cv)
  386. if &#39;svm&#39; in model_type:
  387. preds_proba = preds
  388. else:
  389. preds_proba = m.predict_proba(X_val_cv)[:, 1]
  390. # add scores
  391. for s in scorers.keys():
  392. scorer = scorers[s]
  393. if &#39;roc&#39; in s or &#39;curve&#39; in s:
  394. scores_cv[s].append(scorer(Y_val_cv, preds_proba))
  395. else:
  396. scores_cv[s].append(scorer(Y_val_cv, preds))
  397. imps[&#39;model&#39;].append(deepcopy(m))
  398. imps[&#39;imps&#39;].append(get_feature_importance(m, model_type, X_val_cv, Y_val_cv))
  399. # save results
  400. # os.makedirs(out_dir, exist_ok=True)
  401. results = {&#39;metrics&#39;: list(scorers.keys()),
  402. &#39;num_pts_by_fold_cv&#39;: np.array(num_pts_by_fold_cv),
  403. &#39;cv&#39;: scores_cv,
  404. &#39;imps&#39;: imps, # note this contains the model
  405. &#39;feat_names&#39;: feat_names,
  406. &#39;feature_selector&#39;: feature_selector,
  407. &#39;feature_selection_num&#39;: feature_selection_num,
  408. &#39;model_type&#39;: model_type,
  409. &#39;balancing&#39;: balancing,
  410. &#39;feat_names_selected&#39;: np.array(feat_names)[support],
  411. &#39;calibrated&#39;: calibrated
  412. }
  413. pkl.dump(results, open(out_name, &#39;wb&#39;))</code></pre>
  414. </details>
  415. </dd>
  416. </dl>
  417. </section>
  418. <section>
  419. </section>
  420. </article>
  421. <nav id="sidebar">
  422. <h1>Index</h1>
  423. <div class="toc">
  424. <ul></ul>
  425. </div>
  426. <ul id="index">
  427. <li><h3>Super-module</h3>
  428. <ul>
  429. <li><code><a title="src" href="index.html">src</a></code></li>
  430. </ul>
  431. </li>
  432. <li><h3><a href="#header-functions">Functions</a></h3>
  433. <ul class="">
  434. <li><code><a title="src.train.balance" href="#src.train.balance">balance</a></code></li>
  435. <li><code><a title="src.train.get_feature_importance" href="#src.train.get_feature_importance">get_feature_importance</a></code></li>
  436. <li><code><a title="src.train.train" href="#src.train.train">train</a></code></li>
  437. </ul>
  438. </li>
  439. </ul>
  440. </nav>
  441. </main>
  442. <footer id="footer">
  443. <p>Generated by <a href="https://pdoc3.github.io/pdoc"><cite>pdoc</cite> 0.7.2</a>.</p>
  444. </footer>
  445. <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
  446. <script>hljs.initHighlightingOnLoad()</script>
  447. </body>
  448. </html>
Tip!

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

Comments

Loading...