-
Notifications
You must be signed in to change notification settings - Fork 1
/
mimic_iii_train.py
180 lines (147 loc) · 5.64 KB
/
mimic_iii_train.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
import torch
from tqdm import tqdm
import pickle
import numpy as np
from src.model.mimic_model import MIMICModel
from src.model.mimic_lstm_model import MIMICLSTMModel
from src.model.mimic_gru_model import MIMICGRUModel
from src.utils.mimic_iii_data import MIMICIIIData
from src.utils.data_prep import MortalityDataPrep
'''
!!!! Important !!!!!!!
Input arguments like model_type and cell type are crucial.
'''
args = {
'epochs':100,
'batch_size': 64,
'input_size': 1, #automatically picked from data
'model_type': 'RIM', # type of model RIM, LSTM, GRU
'hidden_size': 100,
'num_rims': 6,
'rnn_cell': 'LSTM', # type of cell LSTM, or GRU
'input_key_size': 64,
'input_value_size': 400,
'input_query_size': 64,
'num_input_heads': 1,
'input_dropout': 0.1,
'comm_key_size': 32,
'comm_value_size': 100,
'comm_query_size': 32,
'num_comm_heads': 2,
'comm_dropout': 0.1,
'active_rims': 4,
'static_features':17, #automatically picked from data
'need_data_preprocessing': False,
'raw_data_file_path' :'data/mimic_iii/test_dump/all_hourly_data.pkl',
'processed_data_path':'data/mimic_iii/preprocessed/mortality_and_los/test',
'input_file_path':'data/mimic_iii/preprocessed/mortality_and_los/x_y_statics_23944.npz'
}
torch.manual_seed(10)
np.random.seed(10)
torch.cuda.manual_seed(10)
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
# Data preprocessing
if(args['need_data_preprocessing']):
prep_data = MortalityDataPrep(args['raw_data_file_path'])
_, _, _, args['input_file_path'] = prep_data.preprocess(True, args['processed_data_path'])
del _
# data loader
data = MIMICIIIData(args['batch_size'], 24, args['input_file_path'])
args['input_size'] = data.input_size()
args['static_features'] = data.static_features_size()
if args['model_type'] == 'LSTM':
model = MIMICLSTMModel(args)
elif args['model_type'] == 'GRU':
model = MIMICGRUModel(args)
else:
model = MIMICModel(args)
model.to(device)
print(f'Model: \n {model}')
save_dir = 'mimic/models'
log_dir = 'mimic/logs'
def eval_model(model, data, data_getter_func):
accuracy = 0
model.eval()
with torch.no_grad():
for i in tqdm(range(data.valid_len())):
x, y, statics = data_getter_func(i)
x = model.to_device(x)
y = model.to_device(y).float()
statics = model.to_device(statics)
predictions = model(x, statics)
probs = torch.round(torch.sigmoid(predictions))
correct = probs.view(-1) == y
accuracy += correct.sum().item()
accuracy /= data.dev_instances
return accuracy
def test_model(model, data, data_getter_func):
accuracy = 0
model.eval()
with torch.no_grad():
for i in tqdm(range(data.test_len())):
x, y, statics = data_getter_func(i)
x = model.to_device(x)
y = model.to_device(y).float()
statics = model.to_device(statics)
predictions = model(x, statics)
probs = torch.round(torch.sigmoid(predictions))
correct = probs.view(-1) == y
accuracy += correct.sum().item()
accuracy /= data.test_instances
return accuracy
def train_model(model, epochs, data):
acc = []
train_acc = []
test_acc = []
loss_stats = []
ctr = 0
start_epochs = 0
optimizer = torch.optim.Adam(model.parameters(), lr = 0.001)
print(f"Training, Validating, and Testing: {args['model_type']} model with {args['rnn_cell']} cell ")
for epoch in range(start_epochs, epochs):
print(f'EPOCH: {epoch +1}')
epoch_loss = 0.0
iter_ctr = 0.0
t_accuracy = 0
norm = 0
model.train()
for i in tqdm(range(data.train_len())):
iter_ctr += 1
x, y, static = data.train_get(i)
x = model.to_device(x)
static = model.to_device(static)
y = model.to_device(y)
output, l = model(x, static, y)
optimizer.zero_grad()
l.backward()
optimizer.step()
norm += model.grad_norm()
epoch_loss += l.item()
predictions = torch.round(output)
correct = predictions.view(-1) == y.long()
t_accuracy += correct.sum().item()
ctr += 1
validation_accuracy = eval_model(model, data, data.valid_get)
test_accuracy = test_model(model, data, data.test_get)
print(f'epoch loss: {epoch_loss}, taining accuracy: {t_accuracy/data.train_instances}, validation accuracy: {validation_accuracy}, Test accuracy: {test_accuracy}, norm: {norm / iter_ctr}')
print("saving the models state...")
model_state = {
'net': model.state_dict(),
'epochs': epoch,
'ctr': ctr
}
with open(f"{save_dir}/{args['model_type']}_model.pt", 'wb') as f:
torch.save(model_state, f)
loss_stats.append((ctr,epoch_loss/iter_ctr))
acc.append((epoch,(validation_accuracy)))
train_acc.append((epoch, (t_accuracy/data.train_instances)))
test_acc.append((epoch, (test_accuracy)))
with open(f"{log_dir}/{args['model_type']}_lossstats.pickle",'wb') as f:
pickle.dump(loss_stats,f)
with open(f"{log_dir}/{args['model_type']}_accstats.pickle",'wb') as f:
pickle.dump(acc,f)
with open(f"{log_dir}/{args['model_type']}_train_acc.pickle",'wb') as f:
pickle.dump(train_acc,f)
with open(f"{log_dir}/{args['model_type']}_test_acc.pickle", 'wb') as f:
pickle.dump(test_acc, f)
train_model(model, args['epochs'], data)