forked from pat-jj/GraphCare
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ehr_models.py
165 lines (144 loc) · 5.77 KB
/
ehr_models.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
from pyhealth.datasets import MIMIC3Dataset, MIMIC4Dataset
from graphcare_.task_fn import drug_recommendation_fn, drug_recommendation_mimic4_fn, mortality_prediction_mimic3_fn, readmission_prediction_mimic3_fn, length_of_stay_prediction_mimic3_fn, length_of_stay_prediction_mimic4_fn, mortality_prediction_mimic4_fn, readmission_prediction_mimic4_fn
from pyhealth.datasets import get_dataloader
from graphcare_ import split_by_patient
import pickle
from pyhealth.trainer import Trainer
import torch
from pyhealth.models import Transformer, RETAIN, SafeDrug, MICRON, CNN, RNN, GAMENet
from collections import defaultdict
import json
tasks = \
[
# "mortality",
# "readmission",
# "lenofstay",
"drugrec"
]
train_ratios = \
[
# 0.001,
# 0.002,
# 0.003,
# 0.004,
# 0.005,
# 0.006,
# 0.007,
# 0.008,
# 0.009,
# 0.01,
# 0.02,
# 0.03,
# 0.04,
# 0.05,
# 0.06,
# 0.07,
# 0.08,
# 0.09,
# 0.1,
# 0.3,
# 0.50,
# 0.7,
# 0.9,
1.0
]
device = torch.device('cuda:4' if torch.cuda.is_available() else 'cpu')
for task in tasks:
print("task: ", task)
if task == "mortality" or task == "readmission":
with open(f'/data/pj20/exp_data/ccscm_ccsproc_atc3/sample_dataset_mimic3_{task}_th015.pkl', 'rb') as f:
sample_dataset = pickle.load(f)
else:
with open(f'/data/pj20/exp_data/ccscm_ccsproc/sample_dataset_mimic3_{task}_th015.pkl', 'rb') as f:
sample_dataset = pickle.load(f)
for train_ratio in train_ratios:
if task != "drugrec":
models = [RNN, Transformer, RETAIN]
else:
models = [
# Transformer,
# RETAIN,
# SafeDrug,
# MICRON,
GAMENet
]
results = defaultdict(list)
for i in range(50):
print("train_ratio: ", train_ratio)
train_dataset, val_dataset, test_dataset = split_by_patient(sample_dataset, [0.8, 0.1, 0.1], train_ratio=train_ratio, seed=528)
train_loader = get_dataloader(train_dataset, batch_size=64, shuffle=True)
val_loader = get_dataloader(val_dataset, batch_size=64, shuffle=False)
test_loader = get_dataloader(test_dataset, batch_size=64, shuffle=False)
for model_ in models:
if task == "mortality" or task == "readmission":
model = model_(
dataset=sample_dataset,
feature_keys=["conditions", "procedures", "drugs"],
label_key="label",
mode="binary",
)
## binary
trainer = Trainer(model=model, device=device, metrics=["pr_auc", "roc_auc", "accuracy", "f1", "jaccard"])
trainer.train(
train_dataloader=train_loader,
val_dataloader=val_loader,
epochs=50,
monitor="accuracy",
)
elif task == "lenofstay":
model = model_(
dataset=sample_dataset,
feature_keys=["conditions", "procedures"],
label_key="label",
mode="multiclass",
)
## multi-class
trainer = Trainer(model=model, device=device, metrics=["roc_auc_weighted_ovr", "cohen_kappa", "accuracy", "f1_weighted"])
trainer.train(
train_dataloader=train_loader,
val_dataloader=val_loader,
epochs=50,
monitor="roc_auc_weighted_ovr",
)
elif task == "drugrec":
try:
model = model_(
dataset=sample_dataset,
feature_keys=["conditions", "procedures"],
label_key="drugs",
mode="multilabel",
)
except:
model = model_(dataset=sample_dataset)
## multi-label
trainer = Trainer(model=model, device=device, metrics=["pr_auc_samples", "roc_auc_samples", "f1_samples", "jaccard_samples"])
try:
trainer.train(
train_dataloader=train_loader,
val_dataloader=val_loader,
epochs=50,
monitor="pr_auc_samples",
)
except:
try:
results[model_.__name__].append(trainer.evaluate(val_loader))
except:
continue
continue
results[model_.__name__].append(trainer.evaluate(val_loader))
avg_results = defaultdict(dict)
for k, v in results.items():
for k_, v_ in v[0].items():
avg_results[k][k_] = sum([vv[k_] for vv in v]) / len(v)
import numpy as np
# calculate standard deviation
variation_results = defaultdict(dict)
for k, v in results.items():
for k_, v_ in v[0].items():
variation_results[k][k_] = np.std([vv[k_] for vv in v])
print(avg_results)
print(variation_results)
with open(f"./ehr_training_result/avg_results_{task}_{train_ratio}.json", "w") as f:
json.dump(avg_results, f, indent=6)
with open(f"./ehr_training_result/variation_results_{task}_{train_ratio}.json", "w") as f:
json.dump(variation_results, f, indent=6)