-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathrun_model.py
1647 lines (1590 loc) · 78.8 KB
/
run_model.py
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import atexit
import os
import re
import sys
import warnings
from argparse import ArgumentParser
from decimal import Decimal
from glob import glob
from pprint import pprint
from shutil import rmtree
from tempfile import mkdtemp, gettempdir
from traceback import format_exception_only
warnings.filterwarnings('ignore', category=FutureWarning,
module='sklearn.utils.deprecation')
warnings.filterwarnings('ignore', category=FutureWarning,
module='rpy2.robjects.pandas2ri')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import rpy2.rinterface_lib.embedded as r_embedded
r_embedded.set_initoptions(
('rpy2', '--quiet', '--no-save', '--max-ppsize=500000'))
import rpy2.robjects as robjects
import seaborn as sns
from eli5 import explain_weights_df
from joblib import Memory, Parallel, delayed, dump, parallel_backend
from matplotlib.offsetbox import AnchoredText
from pandas.api.types import (
is_bool_dtype, is_categorical_dtype, is_integer_dtype, is_float_dtype,
is_object_dtype, is_string_dtype)
from rpy2.robjects import numpy2ri, pandas2ri
from rpy2.robjects.packages import importr
from scipy.stats import iqr
from sklearn.base import BaseEstimator, clone
from sklearn.compose import ColumnTransformer
from sklearn.exceptions import FitFailedWarning
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (auc, average_precision_score,
balanced_accuracy_score, precision_recall_curve,
roc_auc_score, roc_curve)
from sklearn.model_selection import ParameterGrid, RepeatedStratifiedKFold
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import (OneHotEncoder, OrdinalEncoder,
StandardScaler)
from sklearn.svm import SVC
from sklearn.utils import check_random_state, _determine_key_type
from sksurv.metrics import concordance_index_censored
from sksurv.util import Surv
from tabulate import tabulate
numpy2ri.activate()
pandas2ri.activate()
from sklearn_extensions.compose import ExtendedColumnTransformer
from sklearn_extensions.feature_selection import (
EdgeR, EdgeRFilterByExpr, ExtendedRFE, Limma, SelectFromModel)
from sklearn_extensions.linear_model import CachedLogisticRegression
from sklearn_extensions.model_selection import (
ExtendedGridSearchCV, RepeatedStratifiedGroupKFold, shuffle_y)
from sklearn_extensions.pipeline import (ExtendedPipeline,
transform_feature_meta)
from sklearn_extensions.preprocessing import EdgeRTMMLogCPM
from sksurv_extensions.model_selection import (
RepeatedSurvivalStratifiedKFold, SurvivalStratifiedShuffleSplit,
SurvivalStratifiedSampleFromGroupShuffleSplit)
from sksurv_extensions.linear_model import (
CachedExtendedCoxnetSurvivalAnalysis, MetaCoxnetSurvivalAnalysis)
def warning_format(message, category, filename, lineno, file=None, line=None):
return ' {}: {}'.format(category.__name__, message)
def load_dataset(dataset_file):
dataset_name, file_extension = os.path.splitext(
os.path.split(dataset_file)[1])
if not os.path.isfile(dataset_file) or file_extension.lower() != '.rds':
raise IOError('File does not exist/invalid: {}'.format(dataset_file))
eset = r_base.readRDS(dataset_file)
X = pd.DataFrame(r_base.t(r_biobase.exprs(eset)),
columns=r_biobase.featureNames(eset),
index=r_biobase.sampleNames(eset))
sample_meta = r_biobase.pData(eset)
if analysis == 'surv':
y = Surv.from_dataframe('Status', 'Survival_in_days', sample_meta)
else:
y = np.array(sample_meta['Class'], dtype=int)
if 'Group' in sample_meta.columns:
groups = np.array(sample_meta['Group'], dtype=int)
_, group_indices, group_counts = np.unique(
groups, return_inverse=True, return_counts=True)
if ('GroupWeight' in sample_meta.columns
and sample_meta['GroupWeight'].unique().size > 1):
group_weights = np.array(sample_meta['GroupWeight'], dtype=float)
else:
group_weights = None
sample_weights = (np.max(group_counts) / group_counts)[group_indices]
else:
groups = None
group_weights = None
sample_weights = None
try:
feature_meta = r_biobase.fData(eset)
feature_meta_category_cols = (
feature_meta.select_dtypes(include='category').columns)
feature_meta[feature_meta_category_cols] = (
feature_meta[feature_meta_category_cols].astype(str))
except ValueError:
feature_meta = pd.DataFrame(index=r_biobase.featureNames(eset))
new_feature_names = []
if penalty_factor_meta_col in feature_meta.columns:
raise RuntimeError('{} column already exists in feature_meta'
.format(penalty_factor_meta_col))
feature_meta[penalty_factor_meta_col] = 1
for sample_meta_col in sample_meta_cols:
if sample_meta_col not in sample_meta.columns:
raise RuntimeError('{} column does not exist in sample_meta'
.format(sample_meta_col))
if sample_meta_col in X.columns:
raise RuntimeError('{} column already exists in X'
.format(sample_meta_col))
is_category = (is_categorical_dtype(sample_meta[sample_meta_col])
or is_object_dtype(sample_meta[sample_meta_col])
or is_string_dtype(sample_meta[sample_meta_col]))
if not is_category:
X[sample_meta_col] = sample_meta[sample_meta_col]
new_feature_names.append(sample_meta_col)
elif sample_meta_col in ordinal_encoder_categories:
if sample_meta_col not in ordinal_encoder_categories:
raise RuntimeError('No ordinal encoder categories config '
'exists for {}'.format(sample_meta_col))
if sample_meta[sample_meta_col].unique().size > 1:
ode = OrdinalEncoder(categories=[
ordinal_encoder_categories[sample_meta_col]])
ode.fit(sample_meta[[sample_meta_col]])
X[sample_meta_col] = ode.transform(
sample_meta[[sample_meta_col]])
new_feature_names.append(sample_meta_col)
else:
num_categories = sample_meta[sample_meta_col][
sample_meta[sample_meta_col] != 'NA'].unique().size
if num_categories > 2:
ohe_drop = (['NA'] if 'NA' in
sample_meta[sample_meta_col].values else None)
ohe = OneHotEncoder(drop=ohe_drop, sparse=False)
ohe.fit(sample_meta[[sample_meta_col]])
new_sample_meta_cols = []
for category in ohe.categories_[0]:
if category == 'NA':
continue
new_sample_meta_col = '{}_{}'.format(
sample_meta_col, category).replace(' ', '_')
new_sample_meta_cols.append(new_sample_meta_col)
X = X.join(pd.DataFrame(
ohe.transform(sample_meta[[sample_meta_col]]),
index=sample_meta[[sample_meta_col]].index,
columns=new_sample_meta_cols), sort=False)
new_feature_names.extend(new_sample_meta_cols)
elif num_categories == 2:
ohe = OneHotEncoder(drop='first', sparse=False)
ohe.fit(sample_meta[[sample_meta_col]])
category = ohe.categories_[0][1]
new_sample_meta_col = '{}_{}'.format(
sample_meta_col, category).replace(' ', '_')
X[new_sample_meta_col] = ohe.transform(
sample_meta[[sample_meta_col]])
new_feature_names.append(new_sample_meta_col)
new_feature_meta = pd.DataFrame(index=new_feature_names)
for feature_meta_col in feature_meta.columns:
if (is_categorical_dtype(feature_meta[feature_meta_col])
or is_object_dtype(feature_meta[feature_meta_col])
or is_string_dtype(feature_meta[feature_meta_col])):
new_feature_meta[feature_meta_col] = ''
elif (is_integer_dtype(feature_meta[feature_meta_col])
or is_float_dtype(feature_meta[feature_meta_col])):
new_feature_meta[feature_meta_col] = 0
elif is_bool_dtype(feature_meta[feature_meta_col]):
new_feature_meta[feature_meta_col] = False
new_feature_meta[penalty_factor_meta_col] = 0
feature_meta = feature_meta.append(new_feature_meta, verify_integrity=True)
return (dataset_name, X, y, groups, group_weights, sample_weights,
sample_meta, feature_meta)
def get_col_trf_col_grps(X, col_trf_pat_grps):
X_ct = X.copy()
col_trf_col_grps = []
for col_trf_pats in col_trf_pat_grps:
col_trf_cols = []
for pattern in col_trf_pats:
col_trf_cols.append(X_ct.columns.str.contains(pattern, regex=True))
X_ct = X_ct.loc[:, col_trf_cols[0]]
col_trf_col_grps.append(col_trf_cols)
return col_trf_col_grps
def setup_pipe_and_param_grid(X):
clf_c = np.logspace(-5, 3, 9)
l1_ratio = np.array([0.1, 0.3, 0.5, 0.7, 0.8, 0.9, 0.95, 0.99, 1.])
skb_k = np.insert(np.linspace(2, 400, num=200, dtype=int), 0, 1)
sfm_c = (np.logspace(-2, 3, 6) if data_type == 'kraken' else
np.logspace(-2, 1, 4))
# prognosis: coxnet
if analysis == 'surv':
if data_type == 'kraken':
pipe = ExtendedPipeline(
memory=memory,
param_routing={'srv1': ['feature_meta']},
steps=[
('trf0', StandardScaler()),
('srv1', MetaCoxnetSurvivalAnalysis(
estimator=CachedExtendedCoxnetSurvivalAnalysis(
alpha_min_ratio=0.01, fit_baseline_model=True,
max_iter=1000000, memory=memory, n_alphas=100,
penalty_factor_meta_col=penalty_factor_meta_col,
normalize=False, penalty_factor=None)))])
param_grid_dict = {'srv1__estimator__l1_ratio': l1_ratio}
else:
col_trf_col_grps = get_col_trf_col_grps(X, [['^ENSG.+$']])
pipe = ExtendedPipeline(
memory=memory,
param_routing={'srv2': ['feature_meta'],
'trf0': ['sample_meta']},
steps=[
('trf0', ExtendedColumnTransformer(
n_jobs=1,
param_routing={'trf0': ['sample_meta']},
remainder='passthrough',
transformers=[
('trf0', ExtendedPipeline(
memory=memory,
param_routing={'slr0': ['sample_meta'],
'trf1': ['sample_meta']},
steps=[
('slr0', EdgeRFilterByExpr(
is_classif=False)),
('trf1', EdgeRTMMLogCPM(
prior_count=1))]),
col_trf_col_grps[0][0])])),
('trf1', StandardScaler()),
('srv2', MetaCoxnetSurvivalAnalysis(
estimator=CachedExtendedCoxnetSurvivalAnalysis(
alpha_min_ratio=0.01, fit_baseline_model=True,
max_iter=1000000, memory=memory, n_alphas=100,
penalty_factor_meta_col=penalty_factor_meta_col,
normalize=False, penalty_factor=None)))])
param_grid_dict = {'srv2__estimator__l1_ratio': l1_ratio}
# drug response: svm-rfe
elif args.model_type == 'rfe':
if data_type == 'kraken':
pipe = ExtendedPipeline(
memory=memory,
param_routing={'clf1': ['feature_meta', 'sample_weight']},
steps=[
('trf0', StandardScaler()),
('clf1', ExtendedRFE(
estimator=SVC(
cache_size=2000, class_weight='balanced',
kernel='linear', max_iter=int(1e8),
random_state=random_seed),
memory=memory, n_features_to_select=None,
penalty_factor_meta_col=penalty_factor_meta_col,
reducing_step=False, step=1, tune_step_at=None,
tuning_step=1))])
param_grid_dict = {'clf1__estimator__C': clf_c,
'clf1__n_features_to_select': skb_k}
else:
col_trf_col_grps = get_col_trf_col_grps(X, [['^ENSG.+$']])
pipe = ExtendedPipeline(
memory=memory,
param_routing={'clf2': ['feature_meta', 'sample_weight'],
'trf0': ['sample_meta']},
steps=[
('trf0', ExtendedColumnTransformer(
n_jobs=1,
param_routing={'trf0': ['sample_meta']},
remainder='passthrough',
transformers=[
('trf0', ExtendedPipeline(
memory=memory,
param_routing={'slr0': ['sample_meta'],
'trf1': ['sample_meta']},
steps=[
('slr0', EdgeRFilterByExpr(
is_classif=True)),
('trf1', EdgeRTMMLogCPM(
prior_count=1))]),
col_trf_col_grps[0][0])])),
('trf1', StandardScaler()),
('clf2', ExtendedRFE(
estimator=SVC(
cache_size=2000, class_weight='balanced',
kernel='linear', max_iter=int(1e8),
random_state=random_seed),
memory=memory, n_features_to_select=None,
penalty_factor_meta_col=penalty_factor_meta_col,
reducing_step=True, step=0.05, tune_step_at=1300,
tuning_step=1))])
param_grid_dict = {'clf2__estimator__C': clf_c,
'clf2__n_features_to_select': skb_k}
# drug response: elasticnet logistic regression
elif args.model_type == 'lgr':
if data_type == 'kraken':
col_trf_col_grps = get_col_trf_col_grps(
X, [['^(?!gender_male|age_at_diagnosis|tumor_stage).*$',
'^(?:gender_male|age_at_diagnosis|tumor_stage)$']])
pipe = ExtendedPipeline(
memory=memory,
param_routing={'clf1': ['sample_weight'],
'trf0': ['sample_weight']},
steps=[
('trf0', ExtendedColumnTransformer(
n_jobs=1,
param_routing={'trf0': ['sample_weight']},
remainder='passthrough',
transformers=[
('trf0', ExtendedPipeline(
memory=memory,
param_routing={'slr1': ['sample_weight']},
steps=[
('trf0', StandardScaler()),
('slr1', SelectFromModel(
estimator=CachedLogisticRegression(
class_weight='balanced',
max_iter=5000,
memory=memory,
penalty='elasticnet',
random_state=random_seed,
solver='saga'),
max_features=400,
threshold=1e-10))]),
col_trf_col_grps[0][0]),
('trf1', ExtendedPipeline(
memory=memory,
param_routing=None,
steps=[('trf0', StandardScaler())]),
col_trf_col_grps[0][1])])),
('clf1', LogisticRegression(
class_weight='balanced',
max_iter=5000,
penalty='l2',
random_state=random_seed,
solver='saga'))])
param_grid_dict = {
'clf1__C': clf_c,
'trf0__trf0__slr1__estimator__C': sfm_c,
'trf0__trf0__slr1__estimator__l1_ratio': l1_ratio}
elif data_type == 'htseq':
col_trf_col_grps = get_col_trf_col_grps(
X, [['^ENSG.+$', '^(?!ENSG).*$']])
pipe = ExtendedPipeline(
memory=memory,
param_routing={'clf1': ['sample_weight'],
'trf0': ['sample_meta', 'sample_weight']},
steps=[
('trf0', ExtendedColumnTransformer(
n_jobs=1,
param_routing={'trf0': ['sample_meta',
'sample_weight']},
remainder='passthrough',
transformers=[
('trf0', ExtendedPipeline(
memory=memory,
param_routing={'slr0': ['sample_meta'],
'slr3': ['sample_weight'],
'trf1': ['sample_meta']},
steps=[
('slr0', EdgeRFilterByExpr(
is_classif=True)),
('trf1', EdgeRTMMLogCPM(
prior_count=1)),
('trf2', StandardScaler()),
('slr3', SelectFromModel(
estimator=CachedLogisticRegression(
class_weight='balanced',
max_iter=5000,
memory=memory,
penalty='elasticnet',
random_state=random_seed,
solver='saga'),
max_features=400,
threshold=1e-10))]),
col_trf_col_grps[0][0]),
('trf1', ExtendedPipeline(
memory=memory,
param_routing=None,
steps=[('trf0', StandardScaler())]),
col_trf_col_grps[0][1])])),
('clf1', LogisticRegression(
class_weight='balanced',
max_iter=5000,
penalty='l2',
random_state=random_seed,
solver='saga'))])
param_grid_dict = {
'clf1__C': clf_c,
'trf0__trf0__slr3__estimator__C': sfm_c,
'trf0__trf0__slr3__estimator__l1_ratio': l1_ratio}
else:
col_trf_col_grps = get_col_trf_col_grps(
X, [['^(?!gender_male|age_at_diagnosis|tumor_stage).*$',
'^(?:gender_male|age_at_diagnosis|tumor_stage)$'],
['^ENSG.+$']])
pipe = ExtendedPipeline(
memory=memory,
param_routing={'clf1': ['sample_weight'],
'trf0': ['sample_meta', 'sample_weight']},
steps=[
('trf0', ExtendedColumnTransformer(
n_jobs=1,
param_routing={'trf0': ['sample_meta',
'sample_weight']},
remainder='passthrough',
transformers=[
('trf0', ExtendedPipeline(
memory=memory,
param_routing={'slr2': ['sample_weight'],
'trf0': ['sample_meta']},
steps=[
('trf0', ExtendedColumnTransformer(
n_jobs=1,
param_routing={
'trf0': ['sample_meta']},
remainder='passthrough',
transformers=[
('trf0', ExtendedPipeline(
memory=memory,
param_routing={
'slr0': ['sample_meta'],
'trf1': ['sample_meta']},
steps=[
('slr0', EdgeRFilterByExpr(
is_classif=True)),
('trf1', EdgeRTMMLogCPM(
prior_count=1))]),
col_trf_col_grps[1][0])])),
('trf1', StandardScaler()),
('slr2', SelectFromModel(
estimator=CachedLogisticRegression(
class_weight='balanced',
max_iter=5000,
memory=memory,
penalty='elasticnet',
random_state=random_seed,
solver='saga'),
max_features=400,
threshold=1e-10))]),
col_trf_col_grps[0][0]),
('trf1', ExtendedPipeline(
memory=memory,
param_routing=None,
steps=[('trf0', StandardScaler())]),
col_trf_col_grps[0][1])])),
('clf1', LogisticRegression(
class_weight='balanced',
max_iter=5000,
penalty='l2',
random_state=random_seed,
solver='saga'))])
param_grid_dict = {
'clf1__C': clf_c,
'trf0__trf0__slr2__estimator__C': sfm_c,
'trf0__trf0__slr2__estimator__l1_ratio': l1_ratio}
# drug response: limma/edgeR L2 logistic regression
elif data_type == 'kraken':
col_trf_col_grps = get_col_trf_col_grps(
X, [['^(?!gender_male|age_at_diagnosis|tumor_stage).*$']])
pipe = ExtendedPipeline(
memory=memory,
param_routing={'clf2': ['sample_weight'],
'trf0': ['sample_meta']},
steps=[
('trf0', ExtendedColumnTransformer(
n_jobs=1,
param_routing={'trf0': ['sample_meta']},
remainder='passthrough',
transformers=[
('trf0', ExtendedPipeline(
memory=memory,
param_routing={'slr0': ['sample_meta']},
steps=[
('slr0', Limma(
memory=memory,
robust=True,
trend=True))]),
col_trf_col_grps[0][0])])),
('trf1', StandardScaler()),
('clf2', LogisticRegression(
class_weight='balanced',
max_iter=5000,
penalty='l2',
random_state=random_seed,
solver='saga'))])
param_grid_dict = {'clf2__C': clf_c,
'trf0__trf0__slr0__k': skb_k}
elif data_type == 'htseq':
col_trf_col_grps = get_col_trf_col_grps(X, [['^ENSG.+$']])
pipe = ExtendedPipeline(
memory=memory,
param_routing={'clf2': ['sample_weight'],
'trf0': ['sample_meta']},
steps=[
('trf0', ExtendedColumnTransformer(
n_jobs=1,
param_routing={'trf0': ['sample_meta']},
remainder='passthrough',
transformers=[
('trf0', ExtendedPipeline(
memory=memory,
param_routing={'slr0': ['sample_meta'],
'slr1': ['sample_meta']},
steps=[
('slr0', EdgeRFilterByExpr(
is_classif=True)),
('slr1', EdgeR(
memory=memory,
prior_count=1,
robust=True))]),
col_trf_col_grps[0][0])])),
('trf1', StandardScaler()),
('clf2', LogisticRegression(
class_weight='balanced',
max_iter=5000,
penalty='l2',
random_state=random_seed,
solver='saga'))])
param_grid_dict = {'clf2__C': clf_c,
'trf0__trf0__slr1__k': skb_k}
else:
col_trf_col_grps = get_col_trf_col_grps(
X, [['^(?!gender_male|age_at_diagnosis|tumor_stage).*$'],
['^ENSG.+$']])
pipe = ExtendedPipeline(
memory=memory,
param_routing={'clf2': ['sample_weight'],
'trf0': ['sample_meta']},
steps=[('trf0', ExtendedColumnTransformer(
n_jobs=1,
param_routing={'trf0': ['sample_meta']},
remainder='passthrough',
transformers=[
('trf0', ExtendedPipeline(
memory=memory,
param_routing={'slr1': ['sample_meta'],
'trf0': ['sample_meta']},
steps=[
('trf0', ExtendedColumnTransformer(
n_jobs=1,
param_routing={'trf0': ['sample_meta']},
remainder='passthrough',
transformers=[
('trf0', ExtendedPipeline(
memory=memory,
param_routing={
'slr0': ['sample_meta'],
'trf1': ['sample_meta']},
steps=[
('slr0', EdgeRFilterByExpr(
is_classif=True)),
('trf1', EdgeRTMMLogCPM(
prior_count=1))]),
col_trf_col_grps[1][0])])),
('slr1', Limma(
memory=memory,
robust=True,
trend=True))]),
col_trf_col_grps[0][0])])),
('trf1', StandardScaler()),
('clf2', LogisticRegression(
class_weight='balanced',
max_iter=5000,
penalty='l2',
random_state=random_seed,
solver='saga'))])
param_grid_dict = {'clf2__C': clf_c,
'trf0__trf0__slr1__k': skb_k}
param_grid = [param_grid_dict.copy()]
return pipe, param_grid, param_grid_dict
def col_trf_info(col_trf):
col_trf_col_strs = []
for trf_name, trf_transformer, trf_cols in col_trf.transformers:
col_trf_col_strs.append('{}: {:d}'.format(
trf_name, (np.count_nonzero(trf_cols)
if _determine_key_type(trf_cols) == 'bool'
else trf_cols.shape[0])))
if (isinstance(trf_transformer, Pipeline)
and isinstance(trf_transformer[0], ColumnTransformer)):
col_trf_col_strs.append(col_trf_info(trf_transformer[0]))
return '({})'.format(' '.join(col_trf_col_strs))
def get_param_type(param):
pipe_step_type_regex = re.compile(
r'^({})\d+$'.format('|'.join(pipe_step_types)))
param_parts = param.split('__')
param_parts_start_idx = [i for i, p in enumerate(param_parts)
if pipe_step_type_regex.match(p)][-1]
param_parts[param_parts_start_idx] = pipe_step_type_regex.sub(
r'\1', param_parts[param_parts_start_idx])
param_type = '__'.join(param_parts[param_parts_start_idx:])
return param_type
def fit_pipeline(X, y, steps, params=None, param_routing=None,
fit_params=None):
pipe = ExtendedPipeline(steps, memory=memory, param_routing=param_routing)
if params is None:
params = {}
pipe.set_params(**params)
if fit_params is None:
fit_params = {}
try:
pipe.fit(X, y, **fit_params)
except ArithmeticError as e:
warnings.formatwarning = warning_format
warnings.warn('Estimator fit failed. Details: {}'
.format(format_exception_only(type(e), e)[0]),
category=FitFailedWarning)
pipe = None
if args.scv_verbose == 0:
print('.' if pipe is not None else 'x', end='', flush=True)
return pipe
def calculate_test_scores(estimator, X_test, y_test, metrics,
predict_params=None, score_params=None):
scores = {}
if predict_params is None:
predict_params = {}
if hasattr(estimator, 'decision_function'):
y_score = estimator.decision_function(X_test, **predict_params)
scores['y_score'] = y_score
y_pred = estimator.predict(X_test, **predict_params)
scores['y_pred'] = y_pred
if score_params is None:
score_params = {}
if isinstance(metrics, str):
metrics = [metrics]
for metric in metrics:
if metric in ('concordance_index_censored', 'score'):
scores[metric] = concordance_index_censored(
y_test[y_test.dtype.names[0]], y_test[y_test.dtype.names[1]],
y_pred)[0]
elif metric == 'roc_auc':
scores[metric] = roc_auc_score(
y_test, y_score, **score_params)
scores['fpr'], scores['tpr'], _ = roc_curve(
y_test, y_score, pos_label=1, **score_params)
elif metric == 'balanced_accuracy':
scores[metric] = balanced_accuracy_score(
y_test, y_pred, **score_params)
elif metric == 'average_precision':
scores[metric] = average_precision_score(
y_test, y_score, **score_params)
scores['pre'], scores['rec'], _ = precision_recall_curve(
y_test, y_score, pos_label=1, **score_params)
scores['pr_auc'] = auc(scores['rec'], scores['pre'])
return scores
def get_perm_test_split_data(X, perm_y, cv, cv_params=None):
if cv_params is None:
cv_params = {}
perm_split_idxs = list(cv.split(X, perm_y, **cv_params))
return perm_y, perm_split_idxs
def fit_and_score(estimator, X_train, y_train, X_test, y_test, scoring,
fit_params=None, predict_params=None, score_params=None):
if fit_params is None:
fit_params = {}
estimator.fit(X_train, y_train, **fit_params)
scores = calculate_test_scores(estimator, X_test, y_test, scoring,
predict_params=predict_params,
score_params=score_params)
return scores[scoring]
def get_final_feature_meta(pipe, feature_meta):
for estimator in pipe:
feature_meta = transform_feature_meta(estimator, feature_meta)
final_estimator = pipe[-1]
if isinstance(final_estimator, MetaCoxnetSurvivalAnalysis):
feature_weights = final_estimator.coef_
feature_weights = np.ravel(feature_weights)
feature_mask = feature_weights != 0
if penalty_factor_meta_col in feature_meta.columns:
feature_mask[feature_meta[penalty_factor_meta_col] == 0] = True
feature_meta = feature_meta.copy()
feature_meta = feature_meta.loc[feature_mask]
feature_meta['Weight'] = feature_weights[feature_mask]
else:
feature_weights = explain_weights_df(
final_estimator, feature_names=feature_meta.index.values)
if feature_weights is None and hasattr(final_estimator, 'estimator_'):
feature_weights = explain_weights_df(
final_estimator.estimator_,
feature_names=feature_meta.index.values)
if feature_weights is not None:
feature_weights.set_index('feature', inplace=True,
verify_integrity=True)
feature_weights.columns = map(str.title, feature_weights.columns)
feature_meta = feature_meta.join(feature_weights, how='inner')
if (feature_meta['Weight'] == 0).any():
if penalty_factor_meta_col in feature_meta.columns:
feature_meta = feature_meta.loc[
feature_meta[penalty_factor_meta_col] == 0
or feature_meta['Weight'] != 0]
else:
feature_meta = feature_meta.loc[feature_meta['Weight']
!= 0]
feature_meta.index.rename('Feature', inplace=True)
return feature_meta
def add_param_cv_scores(search, param_grid_dict, param_cv_scores=None):
if param_cv_scores is None:
param_cv_scores = {}
for param, param_values in param_grid_dict.items():
if len(param_values) == 1:
continue
param_cv_values = search.cv_results_['param_{}'.format(param)]
if any(isinstance(v, BaseEstimator) for v in param_cv_values):
param_cv_values = np.array(
['.'.join([type(v).__module__, type(v).__qualname__])
if isinstance(v, BaseEstimator) else v
for v in param_cv_values])
if param not in param_cv_scores:
param_cv_scores[param] = {}
for metric in metrics:
if metric not in param_cv_scores[param]:
param_cv_scores[param][metric] = {'scores': [], 'stdev': []}
param_metric_scores = param_cv_scores[param][metric]['scores']
param_metric_stdev = param_cv_scores[param][metric]['stdev']
for param_value_idx, param_value in enumerate(param_values):
mean_cv_scores = (search.cv_results_
['mean_test_{}'.format(metric)]
[param_cv_values == param_value])
std_cv_scores = (search.cv_results_
['std_test_{}'.format(metric)]
[param_cv_values == param_value])
if mean_cv_scores.size > 0:
if param_value_idx < len(param_metric_scores):
param_metric_scores[param_value_idx] = np.append(
param_metric_scores[param_value_idx],
mean_cv_scores[np.argmax(mean_cv_scores)])
param_metric_stdev[param_value_idx] = np.append(
param_metric_stdev[param_value_idx],
std_cv_scores[np.argmax(mean_cv_scores)])
else:
param_metric_scores.append(np.array(
[mean_cv_scores[np.argmax(mean_cv_scores)]]))
param_metric_stdev.append(np.array(
[std_cv_scores[np.argmax(mean_cv_scores)]]))
elif param_value_idx < len(param_metric_scores):
param_metric_scores[param_value_idx] = np.append(
param_metric_scores[param_value_idx], [np.nan])
param_metric_stdev[param_value_idx] = np.append(
param_metric_stdev[param_value_idx], [np.nan])
else:
param_metric_scores.append(np.array([np.nan]))
param_metric_stdev.append(np.array([np.nan]))
return param_cv_scores
def plot_param_cv_metrics(model_name, param_grid_dict, param_cv_scores):
metric_colors = sns.color_palette(args.sns_color_palette, len(metrics))
for param in param_cv_scores:
mean_cv_scores, std_cv_scores = {}, {}
for metric in metrics:
param_metric_scores = param_cv_scores[param][metric]['scores']
param_metric_stdev = param_cv_scores[param][metric]['stdev']
if any(len(scores) > 1 for scores in param_metric_scores):
mean_cv_scores[metric], std_cv_scores[metric] = [], []
for param_value_scores in param_metric_scores:
mean_cv_scores[metric].append(
np.nanmean(param_value_scores))
std_cv_scores[metric].append(
np.nanstd(param_value_scores))
else:
mean_cv_scores[metric] = np.ravel(param_metric_scores)
std_cv_scores[metric] = np.ravel(param_metric_stdev)
plt.figure(figsize=(args.fig_width, args.fig_height))
param_type = get_param_type(param)
if param_type in params_lin_xticks:
x_axis = param_grid_dict[param]
if all(0 <= x <= 1 for x in x_axis):
if len(x_axis) <= 15:
plt.xticks(x_axis)
elif len(x_axis) <= 30:
plt.xticks(x_axis)
elif param_type in params_log_xticks:
x_axis = np.ravel(param_grid_dict[param])
plt.xscale('log', base=(2 if np.all(np.frexp(x_axis)[0] == 0.5)
else 10))
elif param_type in params_fixed_xticks:
x_axis = range(len(param_grid_dict[param]))
xtick_labels = [v.split('.')[-1]
if param_type in pipe_step_types
and not args.long_label_names
and v is not None else str(v)
for v in param_grid_dict[param]]
plt.xticks(x_axis, xtick_labels)
else:
raise RuntimeError('No ticks config exists for {}'
.format(param_type))
plt.xlim([min(x_axis), max(x_axis)])
plt.title('Effect of {} on CV Performance Metrics\n{}'
.format(param, model_name), fontsize=args.title_font_size)
plt.xlabel(param, fontsize=args.axis_font_size)
plt.ylabel('CV Score', fontsize=args.axis_font_size)
for metric_idx, metric in enumerate(metrics):
plt.plot(x_axis, mean_cv_scores[metric],
color=metric_colors[metric_idx], lw=2, alpha=0.8,
label='Mean {}'.format(metric_label[metric]))
plt.fill_between(x_axis,
[m - s for m, s in zip(mean_cv_scores[metric],
std_cv_scores[metric])],
[m + s for m, s in zip(mean_cv_scores[metric],
std_cv_scores[metric])],
alpha=0.1, color=metric_colors[metric_idx],
label=(r'$\pm$ 1 std. dev.'
if metric_idx == len(metrics) - 1
else None))
plt.legend(loc='lower right', fontsize='medium')
plt.tick_params(labelsize=args.axis_font_size)
plt.grid(True, alpha=0.3)
def get_coxnet_max_num_alphas(search):
param_combos = ParameterGrid(search.param_grid)
max_num_alphas = 0
pipe = search.estimator
srv_step_name = pipe.steps[-1][0]
cnet_srv_n_param = '{}__estimator__n_alphas'.format(srv_step_name)
for params in param_combos:
if (isinstance(pipe[-1], MetaCoxnetSurvivalAnalysis)
or (srv_step_name in params and isinstance(
params[srv_step_name], MetaCoxnetSurvivalAnalysis))):
max_num_alphas = max(max_num_alphas,
params[cnet_srv_n_param]
if cnet_srv_n_param in params else
params[srv_step_name].estimator.n_alphas
if srv_step_name in params else
pipe[-1].estimator.n_alphas)
return max_num_alphas
def add_coxnet_alpha_param_grid(search, X, y, pipe_fit_params):
cnet_pipes = []
param_combos = ParameterGrid(search.param_grid)
pipe = search.estimator
srv_step_name = pipe.steps[-1][0]
for params in param_combos:
if (isinstance(pipe[-1], MetaCoxnetSurvivalAnalysis)
or (srv_step_name in params and isinstance(
params[srv_step_name], MetaCoxnetSurvivalAnalysis))):
cnet_pipe = clone(pipe)
cnet_pipe.set_params(**params)
cnet_pipe.steps[-1] = (srv_step_name, cnet_pipe[-1].estimator)
for param in cnet_pipe.get_params(deep=True).keys():
param_parts = param.split('__')
if param_parts[-1] == 'fit_baseline_model':
cnet_pipe.set_params(**{param: False})
cnet_pipes.append(cnet_pipe)
print('Generating CoxnetSurvivalAnalysis alpha path for {} pipeline{}'
.format(len(cnet_pipes), 's' if len(cnet_pipes) > 1 else ''),
flush=True, end='\n' if args.scv_verbose > 0 else ' ')
fitted_cnet_pipes = Parallel(
backend=args.parallel_backend, n_jobs=args.n_jobs,
verbose=args.scv_verbose)(
delayed(fit_pipeline)(X, y, cnet_pipe.steps, params=None,
param_routing=cnet_pipe.param_routing,
fit_params=pipe_fit_params)
for cnet_pipe in cnet_pipes)
if args.scv_verbose == 0:
print(flush=True)
if all(p is None for p in fitted_cnet_pipes):
raise RuntimeError('All CoxnetSurvivalAnalysis alpha path pipelines '
'failed')
param_grid = []
cnet_pipes_idx = 0
cnet_srv_a_param = '{}__alpha'.format(srv_step_name)
for params in param_combos:
param_grid.append({k: [v] for k, v in params.items()})
if (isinstance(pipe[-1], MetaCoxnetSurvivalAnalysis)
or (srv_step_name in params and isinstance(
params[srv_step_name], MetaCoxnetSurvivalAnalysis))):
if fitted_cnet_pipes[cnet_pipes_idx] is not None:
param_grid[-1][cnet_srv_a_param] = (
fitted_cnet_pipes[cnet_pipes_idx][-1].alphas_)
else:
del param_grid[-1]
cnet_pipes_idx += 1
search.set_params(param_grid=param_grid)
if args.verbose > 1:
print('Param grid:')
pprint(param_grid)
return search
def update_coxnet_param_grid_dict(search, param_grid_dict):
pipe = search.estimator
srv_step_name = pipe.steps[-1][0]
cnet_srv_a_param = '{}__alpha'.format(srv_step_name)
cnet_srv_l_param = '{}__estimator__l1_ratio'.format(srv_step_name)
cnet_srv_n_param = '{}__estimator__n_alphas'.format(srv_step_name)
if any(p in search.best_params_ for p in (cnet_srv_l_param,
cnet_srv_n_param)):
best_alpha_condition = {k: v for k, v in search.best_params_.items()
if k in (cnet_srv_l_param, cnet_srv_n_param)}
param_grid_dict[cnet_srv_a_param] = list(filter(
lambda params: all(params[k] == [v] for k, v in
best_alpha_condition.items()),
search.param_grid))[0][cnet_srv_a_param]
else:
param_grid_dict[cnet_srv_a_param] = (
search.param_grid[0][cnet_srv_a_param])
return param_grid_dict
def unset_pipe_memory(pipe):
for param, param_value in pipe.get_params(deep=True).items():
if isinstance(param_value, Memory):
pipe.set_params(**{param: None})
if (isinstance(pipe[0], ColumnTransformer)
and hasattr(pipe[0], 'transformers_')):
for _, trf_transformer, _ in pipe[0].transformers_:
if isinstance(trf_transformer, Pipeline):
unset_pipe_memory(trf_transformer)
return pipe
def run_model():
(dataset_name, X, y, groups, group_weights, sample_weights, sample_meta,
feature_meta) = load_dataset(args.dataset)
pipe, param_grid, param_grid_dict = setup_pipe_and_param_grid(X)
pipe_has_penalty_factor = False
for param in pipe.get_params(deep=True).keys():
param_parts = param.split('__')
if param_parts[-1] == 'penalty_factor_meta_col':
pipe.set_params(**{param: penalty_factor_meta_col})
pipe_has_penalty_factor = True
for params in param_grid:
for param_values in params.values():
if any(isinstance(v, BaseEstimator) for v in param_values):
for estimator in param_values:
for param in estimator.get_params(deep=True).keys():
param_parts = param.split('__')
if param_parts[-1] == 'penalty_factor_meta_col':
estimator.set_params(
**{param: penalty_factor_meta_col})
pipe_has_penalty_factor = True
if not pipe_has_penalty_factor:
feature_meta.drop(columns=[penalty_factor_meta_col],
inplace=True)
if groups is not None:
search_param_routing = {'cv': 'groups', 'estimator': [], 'scoring': []}
else:
search_param_routing = None
if pipe.param_routing:
if search_param_routing is None:
search_param_routing = {'estimator': [], 'scoring': []}
for param in [p for l in pipe.param_routing.values() for p in l]:
if param not in search_param_routing['estimator']:
search_param_routing['estimator'].append(param)
search_param_routing['scoring'].append(param)
test_split_params = {'groups': groups} if groups is not None else {}
if analysis == 'surv':
if groups is None:
test_splitter = SurvivalStratifiedShuffleSplit(
n_splits=test_splits, test_size=test_size,
random_state=random_seed)
else:
test_splitter = SurvivalStratifiedSampleFromGroupShuffleSplit(
n_splits=test_splits, test_size=test_size,
random_state=random_seed)
test_split_params['weights'] = group_weights
cv_splitter = RepeatedSurvivalStratifiedKFold(
n_splits=scv_splits, n_repeats=scv_repeats,
random_state=random_seed)
elif (groups is None or 'sample_weight'
not in search_param_routing['estimator']):
test_splitter = RepeatedStratifiedKFold(
n_splits=test_splits, n_repeats=test_repeats,
random_state=random_seed)
cv_splitter = RepeatedStratifiedKFold(
n_splits=scv_splits, n_repeats=scv_repeats,
random_state=random_seed)
else:
test_splitter = RepeatedStratifiedGroupKFold(
n_splits=test_splits, n_repeats=test_repeats,
random_state=random_seed)
cv_splitter = RepeatedStratifiedGroupKFold(