-
Notifications
You must be signed in to change notification settings - Fork 0
/
team_code.py
2936 lines (2669 loc) · 107 KB
/
team_code.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
# Edit this script to add your team's code. Some functions are *required*, but you can edit most parts of the required functions,
# change or remove non-required functions, and add your own functions.
################################################################################
#
# Optional libraries, functions, and variables. You can change or remove them.
#
################################################################################
import json
import os
import random
import re
import time
from typing import Dict, Tuple
import joblib
import librosa
import matplotlib.pyplot as plt
import mne
import numpy as np
import pandas as pd
import timm
import torch
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.impute import SimpleImputer
from sklearn.linear_model import RidgeClassifierCV
from sklearn.metrics import roc_auc_score
from sktime.classification.kernel_based import RocketClassifier
from sktime.transformations.panel.rocket import Rocket
from sktime.utils import mlflow_sktime
import torchvision
import torchvision.models as models
import torchvision.transforms as T
import xgboost as xgb
from torch import nn
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.data import Dataset, DataLoader
from torch.utils.tensorboard import SummaryWriter
import torch.nn.functional as F
from tqdm import tqdm
from helper_code import *
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
################################################################################
#
# Parameters
#
################################################################################
# Recordings to use
MIN_SIGNAL_LENGTH = 600 # seconds # Minimum length of a signal to consider it
SECONDS_TO_IGNORE_AT_START_AND_END_OF_RECORDING = 120
NUM_HOURS_TO_USE = -48 # This currently uses the recording files, not hours
# Filters
FILTER_SIGNALS = True
NO_CHANNELS_W_ARTIFACT_TO_DISCARD_EPOCH = 2 # Allowed number of channels with artifacts in an epoch to still count the epoch as good
NO_CHANNELS_W_ARTIFACT_TO_DISCARD_WINDOW = 4 # Allowed number of channels with artifacts in a window to still count the window as good and replace the channels with artifacts by a random other channel
WINDOW_SIZE_FILTER = 5 # minutes # Window size to keep from each signal (if signal is shorter, the whole signal is kept)
STRIDE_SIZE_FILTER = 1 # minutes # Stride size for windowing
EPOCH_SIZE_FILTER = (
10 # seconds # Epoch size to use for artifact detection within a window
)
LOW_THRESHOLD = -300
HIGH_THRESHOLD = 300
# Torch settings
USE_TORCH = True
USE_GPU = True
USE_ROCKET = True
USE_AGGREGATION = True
AGGREGATION_METHOD = "voting"
DECISION_THRESHOLD = 0.5
VOTING_POS_MAJORITY_THRESHOLD = 0.66
INFUSE_STATIC_FEATURES = True
ONLY_EEG_TORCH = False
ONLY_EEG_ROCKET = False
PARAMS_DEVICE = {"num_workers": min(26, os.cpu_count() - 2)} # os.cpu_count()}
LIM_HOURS_DURING_TRAINING = True # If this is true, only the first NUM_HOURS_TO_USE hours are used for training torch
HOURS_DURING_TRAINING = -24
PARAMS_TORCH = {
"batch_size": 16,
"val_size": 0.1,
"max_epochs": 10,
"pretrained": True,
"learning_rate": 0.00005,
}
USE_BEST_MODEL = False # If this is true, the best model is used for prediction, otherwise the last model is used
# Imputation
IMPUTE = True
IMPUTE_METHOD = "constant" # 'mean', 'median', 'most_frequent', 'constant'
IMPUTE_CONSTANT_VALUE = -1
# EEG usage
EEG_CHANNELS = [
"Fp1",
"Fp2",
"F7",
"F8",
"F3",
"F4",
"T3",
"T4",
"C3",
"C4",
"T5",
"T6",
"P3",
"P4",
"O1",
"O2",
"Fz",
"Cz",
"Pz",
] # ['F3', 'P3', 'F4', 'P4'] # ['Fp1', 'Fp2', 'F7', 'F8', 'F3', 'F4', 'T3', 'T4', 'C3', 'C4', 'T5', 'T6', 'P3', 'P4', 'O1', 'O2', 'Fz', 'Cz', 'Pz', 'Fpz', 'Oz', 'F9']
BIPOLAR_MONTAGES = (
None # Not used in torch. Must have the format [[ch1, ch2], [ch3, ch4], ...]
)
NUM_HOURS_EEG = NUM_HOURS_TO_USE
NUM_HOURS_EEG_TRAINING = HOURS_DURING_TRAINING
# ECG usage
USE_ECG = False
ECG_CHANNELS = ["ECG", "ECGL", "ECGR", "ECG1", "ECG2"] # ECG, ECG1, ECG2, ECGL, ECGR
NUM_HOURS_ECG = NUM_HOURS_TO_USE
NUM_HOURS_ECG_TRAINING = HOURS_DURING_TRAINING
# OTHER usage
USE_OTHER = False
OTHER_CHANNELS = [
"SpO2",
"EMG1",
"EMG2",
"EMG3",
"LAT1",
"LAT2",
"LOC",
"ROC",
"LEG1",
"LEG2",
]
NUM_HOURS_OTHER = NUM_HOURS_TO_USE
NUM_HOURS_OTHER_TRAINING = HOURS_DURING_TRAINING
# REF usage
USE_REF = False
REF_CHANNELS = [
"RAT1",
"RAT2",
"REF",
"C2",
"A1",
"A2",
"BIP1",
"BIP2",
"BIP3",
"BIP4",
"Cb2",
"M1",
"M2",
"In1-Ref2",
"In1-Ref3",
]
NUM_HOURS_REF = NUM_HOURS_TO_USE
NUM_HOURS_REF_TRAINING = HOURS_DURING_TRAINING
# Model and training paramters
C_MODEL = "rf" # "xgb" or "rf
AGG_OVER_CHANNELS = True
AGG_OVER_TIME = True
PARAMS_RF = {
"n_estimators": 100,
"max_depth": 7,
"max_leaf_nodes": None,
"random_state": 42,
"n_jobs": PARAMS_DEVICE["num_workers"],
}
CLASS_WEIGHT = None #{0:2, 1:1} # default is None
PARAMS_XGB = {"max_depth": 8, "eval_metric": "auc", "nthread": 8}
# Tests
assert (ONLY_EEG_TORCH == False) or ((ONLY_EEG_TORCH == True) and (USE_AGGREGATION == True) and (USE_TORCH == True)), "If only torch should be used, torch must be used (USE_TORCH) and aggregated (USE_AGGREGATION)"
assert (ONLY_EEG_TORCH == False) or ((ONLY_EEG_TORCH == True) and (USE_ECG == False) and (USE_OTHER == False) and (USE_REF == False)), "If only torch should be used, no other data can be used"
assert (ONLY_EEG_ROCKET == False) or ((ONLY_EEG_ROCKET == True) and (USE_AGGREGATION == True) and (USE_ROCKET == True)), "If only rocket should be used, rocket must be used (USE_ROCKET) and aggregated (USE_AGGREGATION)"
assert (ONLY_EEG_ROCKET == False) or ((ONLY_EEG_ROCKET == True) and (USE_ECG == False) and (USE_OTHER == False) and (USE_REF == False)), "If only rocket should be used, no other data can be used"
################################################################################
#
# Required functions. Edit these functions to add your code, but do not change
# the arguments of the functions.
#
################################################################################
# Train your model.
def train_challenge_model(data_folder, model_folder, verbose):
print("Starting train_challenge_model...")
print(f"CPU count: {os.cpu_count()}")
print(f"Using: {PARAMS_DEVICE}")
model_folder = model_folder.lower()
# Save all parameters as json file
params_to_store = {
"PARAMS_DEVICE": PARAMS_DEVICE,
"NUM_HOURS_TO_USE": NUM_HOURS_TO_USE,
"SECONDS_TO_IGNORE_AT_START_AND_END_OF_RECORDING": SECONDS_TO_IGNORE_AT_START_AND_END_OF_RECORDING,
"EEG_CHANNELS": EEG_CHANNELS,
"BIPOLAR_MONTAGES": BIPOLAR_MONTAGES,
"NUM_HOURS_EEG": NUM_HOURS_EEG,
"USE_ECG": USE_ECG,
"ECG_CHANNELS": ECG_CHANNELS,
"NUM_HOURS_ECG": NUM_HOURS_ECG,
"USE_OTHER": USE_OTHER,
"OTHER_CHANNELS": OTHER_CHANNELS,
"NUM_HOURS_OTHER": NUM_HOURS_OTHER,
"USE_REF": USE_REF,
"REF_CHANNELS": REF_CHANNELS,
"NUM_HOURS_REF": NUM_HOURS_REF,
"USE_TORCH": USE_TORCH,
"USE_ROCKET": USE_ROCKET,
"IMPUTE": IMPUTE,
"IMPUTE_METHOD": IMPUTE_METHOD,
"IMPUTE_CONSTANT_VALUE": IMPUTE_CONSTANT_VALUE,
"PARAMS_TORCH": PARAMS_TORCH,
"C_MODEL": C_MODEL,
"PARAMS_RF": PARAMS_RF,
"PARAMS_XGB": PARAMS_XGB,
"AGG_OVER_CHANNELS": AGG_OVER_CHANNELS,
"AGG_OVER_TIME": AGG_OVER_TIME,
"USE_AGGREGATION": USE_AGGREGATION,
"AGGREGATION_METHOD": AGGREGATION_METHOD,
"DECISION_THRESHOLD": DECISION_THRESHOLD,
"VOTING_POS_MAJORITY_THRESHOLD": VOTING_POS_MAJORITY_THRESHOLD,
"INFUSE_STATIC_FEATURES": INFUSE_STATIC_FEATURES,
"ONLY_EEG_TORCH": ONLY_EEG_TORCH,
"ONLY_EEG_ROCKET": ONLY_EEG_ROCKET
}
if not os.path.exists(model_folder):
os.makedirs(model_folder)
with open(os.path.join(model_folder, "params.json"), "w") as f:
json.dump(params_to_store, f)
# Parameters
params_torch = PARAMS_TORCH
c_model = C_MODEL
params_rf = PARAMS_RF
params_xgb = PARAMS_XGB
# Find data files.
start_time = time.time()
if verbose >= 1:
print(f"Finding the challenge data in {data_folder}...")
patient_ids = find_data_folders(data_folder)
num_patients = len(patient_ids)
if num_patients == 0:
raise FileNotFoundError("No data was provided.")
# Create a folder for the model if it does not already exist.
os.makedirs(model_folder, exist_ok=True)
# TORCH
torch_model_eeg = None
torch_model_ecg = None
torch_model_other = None
torch_model_ref = None
if USE_ROCKET:
data_set_eeg_raw = RecordingsDataset(
data_folder,
patient_ids=patient_ids,
device='cpu',
group="EEG",
hours_to_use=NUM_HOURS_EEG,
raw=True
)
data_loader_eeg_raw = DataLoader(
data_set_eeg_raw,
batch_size=10,
num_workers=PARAMS_DEVICE["num_workers"],
shuffle=True,
)
clf = RidgeClassifierCV(alphas=np.logspace(-3, 3, 10))
trf = Rocket(num_kernels=1000, n_jobs=1, random_state=1)
print('Start fitting ROCKET...')
trf.fit(np.zeros((1, 19, 38400)))
features_train = pd.DataFrame(columns = range(2*1000))
labels_train = np.empty((0,))
print('Start extracting ROCKET features for RidgeClassifierCV...')
for data in data_loader_eeg_raw:
X_train = data["signal"].cpu().detach().numpy()
y_train = data["label"].cpu().detach().numpy()
features_train = pd.concat([features_train, trf.transform(X_train)], ignore_index=True, sort=False)
labels_train = np.concatenate([labels_train, y_train])
print('ROCKET features extracted')
print('Start training RidgeClassifierCV for ROCKET...')
clf.fit(features_train, labels_train)
print('All ROCKET trained.')
rocket_transform = trf
rocket_model = clf
print('Start predicting ROCKET features ...')
(
output_list_rocket_eeg,
patient_id_list_rocket_eeg,
hour_list_rocket_eeg,
quality_list_rocket_eeg,
) = rocket_prediction(trf, clf, data_loader_eeg_raw)
print("Done with ROCKET. ---")
else:
rocket_transform = None
rocket_model = None
if USE_TORCH:
# Split into train and validation set
num_val = int(num_patients * params_torch["val_size"])
num_train = num_patients - num_val
patient_ids_aux = patient_ids.copy()
random.Random(42).shuffle(patient_ids_aux)
train_ids = patient_ids_aux[:num_train]
val_ids = patient_ids_aux[num_train:]
# Get device
if USE_GPU:
device = torch.device(
"cuda"
if torch.cuda.is_available()
else "mps"
if torch.backends.mps.is_available()
else "cpu"
)
else:
device = torch.device("cpu")
print(f"Using device {device}")
if c_model == "rf":
print(
f"Train with torch and {c_model}:\n torch params: {params_torch},\n {c_model} params: {params_rf}"
)
elif c_model == "xgb":
print(
f"Train with torch and {c_model}:\n torch params: {params_torch},\n {c_model} params: {params_xgb}"
)
else:
raise ValueError(f"No such c_model: {c_model}")\
# Get EEG DL data
if LIM_HOURS_DURING_TRAINING:
hours_to_use = NUM_HOURS_EEG_TRAINING
else:
hours_to_use = None
train_dataset_eeg = RecordingsDataset(
data_folder,
patient_ids=train_ids,
device=device,
group="EEG",
hours_to_use=hours_to_use,
)
val_dataset_eeg = RecordingsDataset(
data_folder,
patient_ids=val_ids,
device=device,
group="EEG",
hours_to_use=hours_to_use,
)
torch_dataset_eeg = RecordingsDataset(
data_folder,
patient_ids=patient_ids,
device=device,
group="EEG",
hours_to_use=NUM_HOURS_EEG,
)
train_loader_eeg = DataLoader(
train_dataset_eeg,
batch_size=params_torch["batch_size"],
num_workers=PARAMS_DEVICE["num_workers"],
shuffle=True,
pin_memory=True,
)
val_loader_eeg = DataLoader(
val_dataset_eeg,
batch_size=params_torch["batch_size"],
num_workers=PARAMS_DEVICE["num_workers"],
shuffle=False,
pin_memory=True,
)
data_loader_eeg = DataLoader(
torch_dataset_eeg,
batch_size=params_torch["batch_size"],
num_workers=PARAMS_DEVICE["num_workers"],
shuffle=False,
pin_memory=True,
)
# Define torch model
torch_model_eeg = get_tv_model(
batch_size=params_torch["batch_size"],
d_size=len(train_loader_eeg),
pretrained=params_torch["pretrained"],
channel_size=len(EEG_CHANNELS),
additional_features=torch_dataset_eeg.num_additional_features
)
# Find last checkpoint
model_folder_eeg = os.path.join(model_folder, "EEG")
checkpoint_path_eeg = get_last_chkpt(model_folder_eeg)
# Train EEG torch model
print("Start training EEG torch model...")
start_time_torch_eeg = time.time()
torch_model_eeg = train_torch_model(
model=torch_model_eeg,
train_loader=train_loader_eeg,
val_loader=val_loader_eeg,
device=device,
params=params_torch,
model_folder=model_folder_eeg,
checkpoint_path=checkpoint_path_eeg,
)
print(
f"Finished training EEG torch model for {params_torch['max_epochs']} epochs after {round((time.time()-start_time_torch_eeg)/60,4)} min. ---"
)
# Get EEG predictions
print("Start predicting EEG torch features ...")
(
output_list_eeg,
patient_id_list_eeg,
hour_list_eeg,
quality_list_eeg,
) = torch_prediction(torch_model_eeg, data_loader_eeg, device)
print("Done with EEG torch.")
if USE_ECG:
# Get ECG DL data
if LIM_HOURS_DURING_TRAINING:
hours_to_use = NUM_HOURS_ECG_TRAINING
else:
hours_to_use = None
train_dataset_ecg = RecordingsDataset(
data_folder,
patient_ids=train_ids,
device=device,
group="ECG",
hours_to_use=hours_to_use,
)
val_dataset_ecg = RecordingsDataset(
data_folder,
patient_ids=val_ids,
device=device,
group="ECG",
hours_to_use=hours_to_use,
)
torch_dataset_ecg = RecordingsDataset(
data_folder,
patient_ids=patient_ids,
device=device,
group="ECG",
hours_to_use=NUM_HOURS_ECG,
)
train_loader_ecg = DataLoader(
train_dataset_ecg,
batch_size=params_torch["batch_size"],
num_workers=PARAMS_DEVICE["num_workers"],
shuffle=True,
pin_memory=True,
)
val_loader_ecg = DataLoader(
val_dataset_ecg,
batch_size=params_torch["batch_size"],
num_workers=PARAMS_DEVICE["num_workers"],
shuffle=False,
pin_memory=True,
)
data_loader_ecg = DataLoader(
torch_dataset_ecg,
batch_size=params_torch["batch_size"],
num_workers=PARAMS_DEVICE["num_workers"],
shuffle=False,
pin_memory=True,
)
# Find last checkpoint
model_folder_ecg = os.path.join(model_folder, "ECG")
checkpoint_path_ecg = get_last_chkpt(model_folder_ecg)
# Define torch model
torch_model_ecg = get_tv_model(
batch_size=params_torch["batch_size"],
d_size=len(train_loader_ecg),
pretrained=params_torch["pretrained"],
channel_size=len(ECG_CHANNELS),
additional_features=torch_dataset_ecg.num_additional_features
)
# Train ECG torch model
print("Start training ECG torch model...")
start_time_torch = time.time()
torch_model_ecg = train_torch_model(
model=torch_model_ecg,
train_loader=train_loader_ecg,
val_loader=val_loader_ecg,
device=device,
params=params_torch,
model_folder=model_folder_ecg,
checkpoint_path=checkpoint_path_ecg,
)
print(
f"Finished training ECG torch model for {params_torch['max_epochs']} epochs after {round((time.time()-start_time_torch)/60,4)} min."
)
# Get ECG predictions
print("Start predicting ECG torch features ...")
(
output_list_ecg,
patient_id_list_ecg,
hour_list_ecg,
quality_list_ecg,
) = torch_prediction(torch_model_ecg, data_loader_ecg, device)
print("Done with ECG torch.")
if USE_REF:
# Get REF DL data
if LIM_HOURS_DURING_TRAINING:
hours_to_use = NUM_HOURS_REF_TRAINING
else:
hours_to_use = None
train_dataset_ref = RecordingsDataset(
data_folder,
patient_ids=train_ids,
device=device,
group="REF",
hours_to_use=hours_to_use,
)
val_dataset_ref = RecordingsDataset(
data_folder,
patient_ids=val_ids,
device=device,
group="REF",
hours_to_use=hours_to_use,
)
torch_dataset_ref = RecordingsDataset(
data_folder,
patient_ids=patient_ids,
device=device,
group="REF",
hours_to_use=NUM_HOURS_REF,
)
train_loader_ref = DataLoader(
train_dataset_ref,
batch_size=params_torch["batch_size"],
num_workers=PARAMS_DEVICE["num_workers"],
shuffle=True,
pin_memory=True,
)
val_loader_ref = DataLoader(
val_dataset_ref,
batch_size=params_torch["batch_size"],
num_workers=PARAMS_DEVICE["num_workers"],
shuffle=False,
pin_memory=True,
)
data_loader_ref = DataLoader(
torch_dataset_ref,
batch_size=params_torch["batch_size"],
num_workers=PARAMS_DEVICE["num_workers"],
shuffle=False,
pin_memory=True,
)
# Find last checkpoint
model_folder_ref = os.path.join(model_folder, "REF")
checkpoint_path_ref = get_last_chkpt(model_folder_ref)
# Define torch model
torch_model_ref = get_tv_model(
batch_size=params_torch["batch_size"],
d_size=len(train_loader_ref),
pretrained=params_torch["pretrained"],
channel_size=len(REF_CHANNELS),
additional_features=torch_dataset_ref.num_additional_features
)
# Train REF torch model
print("Start training REF torch model...")
start_time_torch = time.time()
torch_model_ref = train_torch_model(
model=torch_model_ref,
train_loader=train_loader_ref,
val_loader=val_loader_ref,
device=device,
params=params_torch,
model_folder=model_folder_ref,
checkpoint_path=checkpoint_path_ref,
)
print(
f"Finished training REF torch model for {params_torch['max_epochs']} epochs after {round((time.time()-start_time_torch)/60,4)} min."
)
# Get REF predictions
print("Start predicting REF torch features ...")
(
output_list_ref,
patient_id_list_ref,
hour_list_ref,
quality_list_ref,
) = torch_prediction(torch_model_ref, data_loader_ref, device)
print("Done with REF torch.")
if USE_OTHER:
# Get OTHER DL data
if LIM_HOURS_DURING_TRAINING:
hours_to_use = NUM_HOURS_OTHER_TRAINING
else:
hours_to_use = None
train_dataset_other = RecordingsDataset(
data_folder,
patient_ids=train_ids,
device=device,
group="OTHER",
hours_to_use=hours_to_use,
)
val_dataset_other = RecordingsDataset(
data_folder,
patient_ids=val_ids,
device=device,
group="OTHER",
hours_to_use=hours_to_use,
)
torch_dataset_other = RecordingsDataset(
data_folder,
patient_ids=patient_ids,
device=device,
group="OTHER",
hours_to_use=NUM_HOURS_OTHER,
)
train_loader_other = DataLoader(
train_dataset_other,
batch_size=params_torch["batch_size"],
num_workers=PARAMS_DEVICE["num_workers"],
shuffle=True,
pin_memory=True,
)
val_loader_other = DataLoader(
val_dataset_other,
batch_size=params_torch["batch_size"],
num_workers=PARAMS_DEVICE["num_workers"],
shuffle=False,
pin_memory=True,
)
data_loader_other = DataLoader(
torch_dataset_other,
batch_size=params_torch["batch_size"],
num_workers=PARAMS_DEVICE["num_workers"],
shuffle=False,
pin_memory=True,
)
# Find last checkpoint
model_folder_other = os.path.join(model_folder, "OTHER")
checkpoint_path_other = get_last_chkpt(model_folder_other)
# Define torch model
torch_model_other = get_tv_model(
batch_size=params_torch["batch_size"],
d_size=len(train_loader_other),
pretrained=params_torch["pretrained"],
channel_size=len(OTHER_CHANNELS),
additional_features=torch_dataset_other.num_additional_features
)
# Train OTHER torch model
print("Start training OTHER torch model...")
start_time_torch = time.time()
torch_model_other = train_torch_model(
model=torch_model_other,
train_loader=train_loader_other,
val_loader=val_loader_other,
device=device,
params=params_torch,
model_folder=model_folder_other,
checkpoint_path=checkpoint_path_other,
)
print(
f"Finished training OTHER torch model for {params_torch['max_epochs']} epochs after {round((time.time()-start_time_torch)/60,4)} min."
)
# Get OTHER predictions
print("Start predicting OTHER torch features ...")
(
output_list_other,
patient_id_list_other,
hour_list_other,
quality_list_other,
) = torch_prediction(torch_model_other, data_loader_other, device)
print("Done with OTHER torch.")
print("Done with torch. ---")
else:
if c_model == "rf":
print(
f"Train without torch but with {c_model}:\n {c_model} params: {params_rf}"
)
elif c_model == "xgb":
print(
f"Train without torch but with {c_model}:\n {c_model} params: {params_xgb}"
)
else:
raise ValueError(f"No such c_model: {c_model}")
print("Calculating features...")
features = list()
feature_names = list()
outcomes = list()
patients = list()
hospitals = list()
recording_meta_infos = list()
cpcs = list()
patient_ids_aux = list()
outcome_probabilities_rocket_eeg_aux = list()
outcome_probabilities_torch_eeg_aux = list()
outcome_probabilities_torch_ecg_aux = list()
outcome_probabilities_torch_ref_aux = list()
outcome_probabilities_torch_other_aux = list()
outcome_flags_rocket_eeg_aux = list()
outcome_flags_torch_eeg_aux = list()
outcome_flags_torch_ecg_aux = list()
outcome_flags_torch_ref_aux = list()
outcome_flags_torch_other_aux = list()
for i in tqdm(range(num_patients)):
if verbose >= 2:
print(" {}/{}...".format(i + 1, num_patients))
# Load data and extract features
patient_metadata = load_challenge_data(data_folder, patient_ids[i])
(
current_features,
current_feature_names,
hospital,
recording_infos,
) = get_features(data_folder, patient_ids[i])
if USE_ROCKET:
(
outcome_probabilities_rocket_eeg,
outcome_flags_rocket_eeg,
rocket_names_eeg,
) = rocket_predictions_for_patient(
output_list_rocket_eeg,
patient_id_list_rocket_eeg,
hour_list_rocket_eeg,
quality_list_rocket_eeg,
patient_ids[i],
hours_to_use=NUM_HOURS_EEG,
group="EEG",
)
if ONLY_EEG_ROCKET:
current_features = outcome_probabilities_rocket_eeg
current_feature_names = rocket_names_eeg
else:
current_features = np.hstack((current_features, outcome_probabilities_rocket_eeg))
current_feature_names = np.hstack((current_feature_names,rocket_names_eeg))
outcome_probabilities_rocket_eeg_aux.append(outcome_probabilities_rocket_eeg)
outcome_flags_rocket_eeg_aux.append(outcome_flags_rocket_eeg)
if USE_TORCH:
# Get torch predictions
(
outcome_probabilities_torch_eeg,
outcome_flags_torch_eeg,
torch_names_eeg,
) = torch_predictions_for_patient(
output_list_eeg,
patient_id_list_eeg,
hour_list_eeg,
quality_list_eeg,
patient_ids[i],
hours_to_use=NUM_HOURS_EEG,
group="EEG",
)
if ONLY_EEG_TORCH:
current_features = outcome_probabilities_torch_eeg
current_feature_names = torch_names_eeg
else:
current_features = np.hstack((current_features, outcome_probabilities_torch_eeg))
current_feature_names = np.hstack((current_feature_names,torch_names_eeg))
outcome_probabilities_torch_eeg_aux.append(outcome_probabilities_torch_eeg)
outcome_flags_torch_eeg_aux.append(outcome_flags_torch_eeg)
if USE_ECG:
(
outcome_probabilities_torch_ecg,
outcome_flags_torch_ecg,
torch_names_ecg,
) = torch_predictions_for_patient(
output_list_ecg,
patient_id_list_ecg,
hour_list_ecg,
quality_list_ecg,
patient_ids[i],
hours_to_use=NUM_HOURS_ECG,
group="ECG",
)
current_features = np.hstack((current_features, outcome_probabilities_torch_ecg))
current_feature_names = np.hstack((current_feature_names,torch_names_ecg))
outcome_probabilities_torch_ecg_aux.append(
outcome_probabilities_torch_ecg
)
outcome_flags_torch_ecg_aux.append(outcome_flags_torch_ecg)
if USE_REF:
(
outcome_probabilities_torch_ref,
outcome_flags_torch_ref,
torch_names_ref,
) = torch_predictions_for_patient(
output_list_ref,
patient_id_list_ref,
hour_list_ref,
quality_list_ref,
patient_ids[i],
hours_to_use=NUM_HOURS_REF,
group="REF",
)
current_features = np.hstack((current_features, outcome_probabilities_torch_ref))
current_feature_names = np.hstack((current_feature_names,torch_names_ref))
outcome_probabilities_torch_ref_aux.append(
outcome_probabilities_torch_ref
)
outcome_flags_torch_ref_aux.append(outcome_flags_torch_ref)
if USE_OTHER:
(
outcome_probabilities_torch_other,
outcome_flags_torch_other,
torch_names_other,
) = torch_predictions_for_patient(
output_list_other,
patient_id_list_other,
hour_list_other,
quality_list_other,
patient_ids[i],
hours_to_use=NUM_HOURS_OTHER,
group="OTHER",
)
current_features = np.hstack((current_features, outcome_probabilities_torch_other))
current_feature_names = np.hstack((current_feature_names,torch_names_other))
outcome_probabilities_torch_other_aux.append(
outcome_probabilities_torch_other
)
outcome_flags_torch_other_aux.append(outcome_flags_torch_other)
# Extract labels.
features.append(current_features)
feature_names.append(current_feature_names)
current_outcome = get_outcome(patient_metadata)
outcomes.append(current_outcome)
current_cpc = get_cpc(patient_metadata)
hospitals.append(hospital)
recording_meta_infos.append(recording_infos)
cpcs.append(current_cpc)
patients.append(patient_ids[i])
features = np.vstack(features)
feature_names = np.vstack(feature_names)
outcomes = np.vstack(outcomes)
patients = np.vstack(patients)
cpcs = np.vstack(cpcs)
hospitals = np.vstack(hospitals)
recording_meta_infos = np.vstack(recording_meta_infos)
# Save the features and outcomes features.
print("Saving features...")
train_pd = pd.DataFrame(features, columns=feature_names[0])
train_pd["patient_ids"] = patients
train_pd["outcome"] = outcomes
train_pd["cpc"] = cpcs
train_pd["hospital"] = hospitals
first_column = train_pd.pop("patient_ids")
train_pd.insert(0, "patient_ids", first_column)
for key in recording_meta_infos[0][0].keys():
values_aux = list()
for i in range(len(recording_meta_infos)):
values_aux.append(recording_meta_infos[i][0][key])
train_pd[key] = values_aux
train_pd.to_csv(os.path.join(model_folder, "train_features.csv"), index=False)
# Impute any missing features.
if IMPUTE:
print("Imputing features...")
imputer = SimpleImputer(
strategy=IMPUTE_METHOD, fill_value=IMPUTE_CONSTANT_VALUE
).fit(features)
features = imputer.transform(features)
else:
imputer = None
# Save the imputed features.
print("Saving imputed features...")
train_imputed_pd = pd.DataFrame(features, columns=feature_names[0])
train_imputed_pd["patient_ids"] = patients
train_imputed_pd["outcome"] = outcomes
train_imputed_pd["cpc"] = cpcs
train_imputed_pd["hospital"] = hospitals
for key in recording_meta_infos[0][0].keys():
values_aux = list()
for i in range(len(recording_meta_infos)):
values_aux.append(recording_meta_infos[i][0][key])
train_imputed_pd[key] = values_aux
train_imputed_pd.to_csv(
os.path.join(model_folder, "train_imputed_features.csv"), index=False
)
# Train the models.
if ONLY_EEG_TORCH or ONLY_EEG_ROCKET:
outcome_model = None
cpc_model = None
else:
print("Start training challenge model...")
if c_model == "rf":
outcome_model = RandomForestClassifier(**params_rf, class_weight=CLASS_WEIGHT)
cpc_model = RandomForestRegressor(**params_rf)
elif c_model == "xgb":
outcome_model = xgb.XGBClassifier(**params_xgb, class_weight=CLASS_WEIGHT)
cpc_model = xgb.XGBRegressor(**params_xgb)
outcome_model.fit(features, outcomes.ravel())
cpc_model.fit(features, cpcs.ravel())
print("Finished training challenge model.")
# Plot and save feature importance.
n = 120
feature_importance = outcome_model.feature_importances_
feature_importance = 100.0 * (feature_importance / feature_importance.max())
sorted_idx = np.argsort(feature_importance)
if len(sorted_idx) > n:
# Create a list of names of the features not being plotted
not_plotted_features = [feature_names[0][i] for i in sorted_idx[:-n]]
not_plotted_features = list(map(str, not_plotted_features))
#print("Features not being plotted:", not_plotted_features)
# Save not_plotted_features as a JSON file
with open(os.path.join(model_folder, "not_plotted_features.json"), 'w') as f:
json.dump(not_plotted_features, f)
# Adjust indices to plot only the top n features
sorted_idx = sorted_idx[-n:]
pos = np.arange(sorted_idx.shape[0]) + 0.5
plt.figure(figsize=(12, min(n / 2, 100)))
plt.barh(pos, feature_importance[sorted_idx], align="center")
plt.yticks(pos, np.array(feature_names[0])[sorted_idx])
plt.xlabel("Relative Importance")
plt.title("Variable Importance")
plt.tight_layout()
plt.savefig(os.path.join(model_folder, "feature_importance.png"))
plt.close()
# Save the models.
save_challenge_model(
model_folder,
imputer,
outcome_model,
cpc_model,
rocket_model,
rocket_transform,
torch_model_eeg=torch_model_eeg,
torch_model_ecg=torch_model_ecg,
torch_model_ref=torch_model_ref,
torch_model_other=torch_model_other,
)
if verbose >= 1:
print(f"Done after {round((time.time()-start_time)/60,4)} min.")
# Load your trained models. This function is *required*. You should edit this function to add your code, but do *not* change the
# arguments of this function.
def load_challenge_models(model_folder, verbose):
model_folder = model_folder.lower()
filename = os.path.join(model_folder, "models.sav")
model = joblib.load(filename)
file_path_eeg = os.path.join(model_folder, "eeg", "checkpoint.pth")
file_path_ecg = os.path.join(model_folder, "ecg", "checkpoint.pth")
file_path_ref = os.path.join(model_folder, "ref", "checkpoint.pth")
file_path_other = os.path.join(model_folder, "other", "checkpoint.pth")
if USE_ROCKET:
model["rocket_eeg"] = mlflow_sktime.load_model(model_uri=os.path.join(model_folder, "eeg", "rocket"))
model["rocket_model_eeg"] = mlflow_sktime.load_model(model_uri=os.path.join(model_folder, "eeg", "rocket_model"))
else:
model["rocket_model_eeg"] = None
model["rocket_eeg"] = None
if USE_TORCH:
model["torch_model_eeg"] = load_last_pt_ckpt(
file_path_eeg, channel_size=len(EEG_CHANNELS)
)
if USE_ECG:
model["torch_model_ecg"] = load_last_pt_ckpt(
file_path_ecg, channel_size=len(ECG_CHANNELS)
)
else:
model["torch_model_ecg"] = None
if USE_REF: