-
Notifications
You must be signed in to change notification settings - Fork 1
/
run_model.py
executable file
·3370 lines (3301 loc) · 130 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
#!/usr/bin/env python
import atexit
import os
import re
import sys
import threading
import warnings
from argparse import ArgumentParser, ArgumentTypeError
from decimal import Decimal
from glob import glob
from itertools import product
from pprint import pprint
from shutil import rmtree
from tempfile import mkdtemp, gettempdir
from traceback import format_exception_only
from uuid import uuid4
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 ro
import seaborn as sns
from joblib import Memory, Parallel, delayed, dump, load, parallel_backend
from joblib.memory import JobLibCollisionWarning
from joblib._memmapping_reducer import TemporaryResourcesManager
from natsort import natsorted
from pandas.api.types import (
is_bool_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 sklearn.base import BaseEstimator, clone
from sklearn.compose import ColumnTransformer
from sklearn.exceptions import ConvergenceWarning, FitFailedWarning
from sklearn.feature_selection import RFE
from sklearn.model_selection import ParameterGrid, ParameterSampler
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import (
MinMaxScaler,
MaxAbsScaler,
OneHotEncoder,
OrdinalEncoder,
PowerTransformer,
RobustScaler,
StandardScaler,
)
from sksurv.base import SurvivalAnalysisMixin
from sksurv.linear_model import CoxnetSurvivalAnalysis
from sksurv.metrics import (
concordance_index_censored,
concordance_index_ipcw,
cumulative_dynamic_auc,
)
from sksurv.svm import FastSurvivalSVM
from sksurv.util import Surv
from tabulate import tabulate
from sklearn_extensions.compose import ExtendedColumnTransformer
from sklearn_extensions.feature_selection import (
ColumnSelector,
ConfidenceThreshold,
CorrelationThreshold,
CountThreshold,
EdgeRFilterByExpr,
ExtendedRFE,
MeanThreshold,
MedianThreshold,
NanoStringEndogenousSelector,
VarianceThreshold,
)
from sklearn_extensions.model_selection import (
ExtendedGridSearchCV,
ExtendedRandomizedSearchCV,
)
from sklearn_extensions.pipeline import ExtendedPipeline, transform_feature_meta
from sklearn_extensions.preprocessing import (
DESeq2Normalizer,
DESeq2WrenchNormalizer,
EdgeRNormalizer,
EdgeRWrenchNormalizer,
LimmaBatchEffectRemover,
LogTransformer,
NanoStringNormalizer,
NanoStringDiffNormalizer,
)
from sklearn_extensions.utils import _determine_key_type
from sksurv_extensions.feature_selection import SelectFromUnivariateSurvivalModel
from sksurv_extensions.model_selection import (
SurvivalStratifiedKFold,
SurvivalStratifiedGroupKFold,
SurvivalStratifiedSampleFromGroupKFold,
RepeatedSurvivalStratifiedKFold,
RepeatedSurvivalStratifiedGroupKFold,
RepeatedSurvivalStratifiedSampleFromGroupKFold,
SurvivalStratifiedShuffleSplit,
SurvivalStratifiedGroupShuffleSplit,
SurvivalStratifiedSampleFromGroupShuffleSplit,
)
from sksurv_extensions.linear_model import (
CachedExtendedCoxnetSurvivalAnalysis,
ExtendedCoxnetSurvivalAnalysis,
ExtendedCoxPHSurvivalAnalysis,
FastCoxPHSurvivalAnalysis,
MetaCoxnetSurvivalAnalysis,
)
from sksurv_extensions.svm import CachedFastSurvivalSVM
def warning_format(message, category, filename, lineno, file=None, line=None):
return " {}: {}".format(category.__name__, message)
def convert_to_memmap(array):
mmap_file = os.path.join(
joblib_temp_folder_mgr.resolve_temp_folder_name(),
"{}-{}-{}.pkl".format(os.getpid(), id(threading.current_thread()), uuid4().hex),
)
if os.path.exists(mmap_file):
os.unlink(mmap_file)
dump(array, mmap_file)
return load(mmap_file, mmap_mode="r+")
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 not in (
".Rda",
".rda",
".RData",
".Rdata",
".Rds",
".rds",
):
raise IOError("File does not exist/invalid: {}".format(dataset_file))
if file_extension in (".Rda", ".rda", ".RData", ".Rdata"):
r_base.load(dataset_file)
eset = ro.globalenv[dataset_name]
else:
eset = r_base.readRDS(dataset_file)
with (ro.default_converter + numpy2ri.converter + pandas2ri.converter).context():
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)
y = Surv.from_dataframe(
args.sample_meta_stat_col, args.sample_meta_surv_col, sample_meta
)
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:
with (ro.default_converter + pandas2ri.converter).context():
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:
with (ro.default_converter + pandas2ri.converter).context():
feature_meta = pd.DataFrame(index=r_biobase.featureNames(eset))
if args.sample_meta_cols:
new_feature_names = []
if args.penalty_factor_meta_col in feature_meta.columns:
raise RuntimeError(
"{} column already exists in feature_meta".format(
args.penalty_factor_meta_col
)
)
feature_meta[args.penalty_factor_meta_col] = 1
for sample_meta_col in args.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 = (
isinstance(sample_meta[sample_meta_col], pd.CategoricalDtype)
or is_object_dtype(sample_meta[sample_meta_col])
or is_string_dtype(sample_meta[sample_meta_col])
)
if args.test_dataset or not is_category:
X[sample_meta_col] = sample_meta[sample_meta_col]
new_feature_names.append(sample_meta_col)
elif (
args.ordinal_encode_cols is not None
and sample_meta_col in args.ordinal_encode_cols
):
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 (
isinstance(feature_meta[feature_meta_col], pd.CategoricalDtype)
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[args.penalty_factor_meta_col] = (
1 if args.penalize_sample_meta_cols else 0
)
feature_meta = pd.concat(
[feature_meta, new_feature_meta], verify_integrity=True
)
col_trf_col_grps = None
if num_col_trfs > 0:
X_ct = X.copy()
col_trf_col_grps = []
for n in range(1, num_col_trfs + 1):
col_trf_cols = []
if hasattr(args, "col_trf_{}_patterns".format(n)):
for pattern in getattr(args, "col_trf_{}_patterns".format(n)):
col_trf_cols.append(X_ct.columns.str.contains(pattern, regex=True))
elif hasattr(args, "col_trf_{}_dtypes".format(n)):
for dtype in getattr(args, "col_trf_{}_dtypes".format(n)):
if dtype == "int":
col_trf_cols.append(
X_ct.dtypes.apply(is_integer_dtype).to_numpy()
)
elif dtype == "float":
col_trf_cols.append(
X_ct.dtypes.apply(is_float_dtype).to_numpy()
)
elif dtype == "category":
col_trf_cols.append(
X_ct.dtypes.apply(
lambda d: (
is_bool_dtype(d)
or isinstance(d, pd.CategoricalDtype)
or is_object_dtype(d)
or is_string_dtype(d)
)
).to_numpy()
)
X_ct = X_ct.loc[:, col_trf_cols[0]]
col_trf_col_grps.append(col_trf_cols)
if col_trf_col_grps and args.max_nbytes is None:
col_trf_col_grps = convert_to_memmap(col_trf_col_grps)
return (
dataset_name,
X,
y,
groups,
group_weights,
sample_weights,
sample_meta,
feature_meta,
col_trf_col_grps,
)
def setup_pipe_and_param_grid(
cmd_pipe_steps, col_trf_col_grps=None, col_trf_grp_idx=0, memory=None, verbose=False
):
pipe_steps = []
pipe_param_routing = None
pipe_step_names = []
pipe_props = {"has_selector": False, "uses_rjava": False}
param_grid = []
param_grid_dict = {}
pipe_step_keys = []
pipe_step_types = []
for step_idx, step_keys in enumerate(cmd_pipe_steps):
if any(k.title() == "None" for k in step_keys):
pipe_step_keys.append(
[k for k in step_keys if k.title() != "None"] + [None]
)
else:
pipe_step_keys.append(step_keys)
if len(step_keys) > 1:
pipe_step_names.append("|".join(step_keys))
else:
pipe_step_names.append(step_keys[0])
for pipe_step_combo in product(*pipe_step_keys):
params = {}
for step_idx, step_key in enumerate(pipe_step_combo):
if step_key:
if step_key not in pipe_config:
raise RuntimeError(
"No pipeline config exists for {}".format(step_key)
)
estimator = pipe_config[step_key]["estimator"]
if isinstance(estimator, SurvivalAnalysisMixin) or (
hasattr(estimator, "estimator")
and isinstance(estimator.estimator, SurvivalAnalysisMixin)
):
step_type = "srv"
if hasattr(estimator, "get_support"):
pipe_props["has_selector"] = True
elif hasattr(estimator, "get_support"):
step_type = "slr"
pipe_props["has_selector"] = True
elif hasattr(estimator, "fit_transform"):
step_type = "trf"
else:
raise RuntimeError(
"Unsupported estimator type {}".format(estimator)
)
if step_idx < len(pipe_steps):
if step_type != pipe_step_types[step_idx]:
raise RuntimeError(
"Different step estimator types: {} {}".format(
step_type, pipe_step_types[step_idx]
)
)
else:
pipe_step_types.append(step_type)
uniq_step_name = "{}{:d}".format(step_type, step_idx)
if "param_grid" in pipe_config[step_key]:
for param, param_values in pipe_config[step_key][
"param_grid"
].items():
if isinstance(param_values, (list, tuple, np.ndarray)):
if (
isinstance(param_values, (list, tuple))
and param_values
or param_values.size > 0
):
uniq_step_param = "{}__{}".format(uniq_step_name, param)
if len(param_values) > 1:
params[uniq_step_param] = param_values
if uniq_step_param not in param_grid_dict:
param_grid_dict[uniq_step_param] = param_values
else:
estimator.set_params(**{param: param_values[0]})
elif param_values is not None:
estimator.set_params(**{param: param_values})
if "param_routing" in pipe_config[step_key]:
if pipe_param_routing is None:
pipe_param_routing = {}
if uniq_step_name in pipe_param_routing:
for param in pipe_config[step_key]["param_routing"]:
if param not in pipe_param_routing[uniq_step_name]:
pipe_param_routing[uniq_step_name] = param
else:
pipe_param_routing[uniq_step_name] = pipe_config[step_key][
"param_routing"
]
if step_idx == len(pipe_steps):
if len(pipe_step_keys[step_idx]) > 1:
pipe_steps.append((uniq_step_name, None))
else:
pipe_steps.append((uniq_step_name, estimator))
if len(pipe_step_keys[step_idx]) > 1:
params[uniq_step_name] = [estimator]
if uniq_step_name not in param_grid_dict:
param_grid_dict[uniq_step_name] = []
if estimator not in param_grid_dict[uniq_step_name]:
param_grid_dict[uniq_step_name].append(estimator)
else:
uniq_step_name = pipe_step_types[step_idx] + str(step_idx)
params[uniq_step_name] = [None]
if uniq_step_name not in param_grid_dict:
param_grid_dict[uniq_step_name] = []
if None not in param_grid_dict[uniq_step_name]:
param_grid_dict[uniq_step_name].append(None)
param_grid.append(params)
pipe = ExtendedPipeline(
pipe_steps, memory=memory, param_routing=pipe_param_routing, verbose=verbose
)
param_grid_estimators = {}
for param, param_values in param_grid_dict.items():
if any(isinstance(v, BaseEstimator) for v in param_values):
param_grid_estimators[param] = param_values
param_grid_dict[param] = sorted(
[
(
".".join([type(v).__module__, type(v).__qualname__])
if isinstance(v, BaseEstimator)
else v
)
for v in param_values
],
key=lambda x: (x is None, x),
)
if isinstance(pipe[0], ColumnTransformer):
pipe = clone(pipe)
col_trf_name, col_trf_estimator = pipe.steps[0]
col_trf_pipe_names = []
col_trf_transformers = []
col_trf_param_grids = []
col_trf_param_routing = None
col_trf_pipe_steps = getattr(
args, "col_trf_{}_pipe_steps".format(col_trf_grp_idx + 1)
)
col_trf_remainder = getattr(
args, "col_trf_{}_remainder".format(col_trf_grp_idx + 1)
)
for trf_idx, trf_pipe_steps in enumerate(col_trf_pipe_steps):
(
trf_pipe,
trf_pipe_step_names,
trf_pipe_props,
trf_param_grid,
trf_param_grid_dict,
trf_param_grid_estimators,
) = setup_pipe_and_param_grid(
trf_pipe_steps,
col_trf_col_grps=col_trf_col_grps,
col_trf_grp_idx=col_trf_grp_idx + 1,
memory=memory,
verbose=verbose,
)
col_trf_pipe_names.append("->".join(trf_pipe_step_names))
uniq_trf_name = "trf{:d}".format(trf_idx)
trf_cols = col_trf_col_grps[col_trf_grp_idx][trf_idx]
col_trf_transformers.append((uniq_trf_name, trf_pipe, trf_cols))
if trf_param_grid:
col_trf_param_grids.append(
[
{
"{}__{}__{}".format(col_trf_name, uniq_trf_name, k): v
for k, v in params.items()
}
for params in trf_param_grid
]
)
for param, param_value in trf_param_grid_dict.items():
param_grid_dict[
"{}__{}__{}".format(col_trf_name, uniq_trf_name, param)
] = param_value
for param, estimator in trf_param_grid_estimators.items():
param_grid_estimators[
"{}__{}__{}".format(col_trf_name, uniq_trf_name, param)
] = clone(estimator)
if trf_pipe.param_routing is not None:
if col_trf_param_routing is None:
col_trf_param_routing = {}
col_trf_param_routing[uniq_trf_name] = list(
{v for l in trf_pipe.param_routing.values() for v in l}
)
for trf_pipe_prop, trf_pipe_prop_value in trf_pipe_props.items():
if trf_pipe_prop_value:
pipe_props[trf_pipe_prop] = trf_pipe_prop_value
if col_trf_param_grids:
final_estimator_param_grid = param_grid.copy()
param_grid = []
for param_grid_combo in product(
final_estimator_param_grid, *col_trf_param_grids
):
param_grid.append(
{k: v for params in param_grid_combo for k, v in params.items()}
)
col_trf_estimator.set_params(
param_routing=col_trf_param_routing,
remainder=col_trf_remainder,
transformers=col_trf_transformers,
)
if col_trf_param_routing is not None:
pipe_param_routing = pipe.param_routing if pipe.param_routing else {}
pipe_param_routing[col_trf_name] = list(
{v for l in col_trf_param_routing.values() for v in l}
)
pipe.set_params(param_routing=pipe_param_routing)
pipe_step_names[0] = "||".join(col_trf_pipe_names)
return (
pipe,
pipe_step_names,
pipe_props,
param_grid,
param_grid_dict,
param_grid_estimators,
)
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(pipeline_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,
memory=None,
verbose=0,
pipe_verbose=False,
):
pipe = ExtendedPipeline(
steps, memory=memory, param_routing=param_routing, verbose=pipe_verbose
)
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 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,
y_train=None,
test_times=None,
predict_params=None,
score_params=None,
):
scores = {}
if predict_params is None:
predict_params = {}
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 == "concordance_index_ipcw":
scores[metric] = concordance_index_ipcw(y_train, y_test, y_pred)[0]
elif metric == "cumulative_dynamic_auc":
scores[metric] = cumulative_dynamic_auc(
y_train, y_test, y_pred, test_times
)[1]
return scores
def get_final_feature_meta(pipe, feature_meta):
for estimator in pipe:
feature_meta = transform_feature_meta(estimator, feature_meta)
feature_weights = None
final_estimator = pipe[-1]
if hasattr(final_estimator, "coef_"):
feature_weights = final_estimator.coef_
elif hasattr(final_estimator, "feature_importances_"):
feature_weights = final_estimator.feature_importances_
elif hasattr(final_estimator, "estimator_"):
if hasattr(final_estimator.estimator_, "coef_"):
feature_weights = final_estimator.estimator_.coef_
elif hasattr(final_estimator.estimator_, "feature_importances_"):
feature_weights = final_estimator.estimator_.feature_importances_
if feature_weights is not None:
if isinstance(final_estimator, CoxnetSurvivalAnalysis) or (
hasattr(final_estimator, "estimator_")
and isinstance(final_estimator.estimator_, CoxnetSurvivalAnalysis)
):
feature_weights = np.ravel(feature_weights)
feature_mask = feature_weights != 0
if args.penalty_factor_meta_col in feature_meta.columns:
feature_mask[feature_meta[args.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]
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 args.scv_scoring:
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"]
if args.param_cv_score_meth == "best":
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]))
elif args.param_cv_score_meth == "all":
for param_value_idx, param_value in enumerate(param_values):
for split_idx in range(search.n_splits_):
split_cv_scores = search.cv_results_[
"split{:d}_test_{}".format(split_idx, metric)
][param_cv_values == param_value]
if split_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],
split_cv_scores,
)
else:
param_metric_scores.append(split_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]
)
else:
param_metric_scores.append([np.nan])
return param_cv_scores
def plot_param_cv_metrics(dataset_name, pipe_name, param_grid_dict, param_cv_scores):
metric_colors = sns.color_palette(args.sns_color_palette, len(args.scv_scoring))
for param in param_cv_scores:
mean_cv_scores, std_cv_scores = {}, {}
for metric in args.scv_scoring:
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 pipeline_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.suptitle(
"Effect of {} on CV Performance Metrics".format(param),
fontsize=args.title_font_size,
)
plt.title(
"{}\n{}".format(dataset_name, pipe_name), fontsize=args.title_font_size - 2
)
plt.xlabel(param, fontsize=args.axis_font_size)
plt.ylabel("CV Score", fontsize=args.axis_font_size)
for metric_idx, metric in enumerate(args.scv_scoring):
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(args.scv_scoring) - 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):
if args.scv_type == "grid":
param_combos = ParameterGrid(search.param_grid)
elif args.scv_type == "rand":
param_combos = ParameterSampler(
search.param_grid, n_iter=args.scv_n_iter, random_state=args.random_seed
)
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 = []
if args.scv_type == "grid":
param_combos = ParameterGrid(search.param_grid)
elif args.scv_type == "rand":
param_combos = ParameterSampler(
search.param_grid, n_iter=args.scv_n_iter, random_state=args.random_seed
)
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(
n_jobs=args.n_jobs,
backend=args.parallel_backend,
max_nbytes=args.max_nbytes,
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,
verbose=args.scv_verbose,
)
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
if args.scv_type == "grid":
search.set_params(param_grid=param_grid)
elif args.scv_type == "rand":
search.set_params(param_distributions=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,
col_trf_col_grps,
) = load_dataset(args.train_dataset)