forked from healthylaife/MIMIC-IV-Data-Pipeline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
digital_twin_ml_model.py
334 lines (283 loc) · 13.5 KB
/
digital_twin_ml_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
import pandas as pd
import numpy as np
import pickle
import torch
import random
from tqdm import tqdm
import time
import os
import importlib
import sys
import numpy as np
import model.evaluation as evaluation
from sklearn.model_selection import KFold
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
import xgboost as xgb
from pathlib import Path
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
import plotly.express as px
from imblearn.over_sampling import RandomOverSampler
from sklearn.metrics import classification_report
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + './../..')
importlib.reload(evaluation)
# MAX_LEN=12
# MAX_COND_SEQ=56
# MAX_PROC_SEQ=40
# MAX_MED_SEQ=15#37
# MAX_LAB_SEQ=899
# MAX_BMI_SEQ=118
class ML_models():
def __init__(self,data_icu,k_fold,model_type,concat,oversampling):
self.data_icu=data_icu
self.k_fold=k_fold
self.model_type=model_type
self.concat=concat
self.oversampling=oversampling
self.loss=evaluation.Loss('cpu',True,True,True,True,True,True,True,True,True,True,True)
self.data_dt_folder = 'data_dt_no_overs/'
self.ml_train()
def create_kfolds(self):
labels=pd.read_csv('./data/csv/labels.csv', header=0)
if (self.k_fold==0):
k_fold=5
self.k_fold=1
else:
k_fold=self.k_fold
hids=labels.iloc[:,0]
y=labels.iloc[:,1]
print("Total Samples",len(hids))
print("Positive Samples",y.sum())
#print(len(hids))
if self.oversampling:
print("=============OVERSAMPLING===============")
oversample = RandomOverSampler(sampling_strategy='minority')
hids=np.asarray(hids).reshape(-1,1)
hids, y = oversample.fit_resample(hids, y)
#print(hids.shape)
hids=hids[:,0]
print("Total Samples",len(hids))
print("Positive Samples",y.sum())
ids=range(0,len(hids))
batch_size=int(len(ids)/k_fold)
k_hids=[]
for i in range(0,k_fold):
rids = random.sample(ids, batch_size)
ids = list(set(ids)-set(rids))
if i==0:
k_hids.append(hids[rids])
else:
k_hids.append(hids[rids])
return k_hids
def ml_train(self):
k_hids=self.create_kfolds()
labels=pd.read_csv('./data/csv/labels.csv', header=0)
for i in range(self.k_fold):
print("==================={0:2d} FOLD=====================".format(i))
test_hids=k_hids[i]
train_ids=list(set([0,1,2,3,4])-set([i]))
train_hids=[]
for j in train_ids:
train_hids.extend(k_hids[j])
print("Test set size: ", len(test_hids))
print("Train set size: ", len(train_hids))
concat_cols=[]
if(self.concat):
dyn=pd.read_csv('./data/csv/'+str(train_hids[0])+'/dynamic.csv',header=[0,1])
dyn_plot = dyn.copy()
# Flatten the MultiIndex columns
dyn_plot.columns = ['_'.join(col).strip() for col in dyn_plot.columns.values]
# Plotting
fig = px.line(dyn_plot, title="Interactive Plot of df_dyn Data")
fig.show()
dyn.columns=dyn.columns.droplevel(0)
cols=dyn.columns
time=dyn.shape[0]
for t in range(time):
cols_t = [x + "_"+str(t) for x in cols]
concat_cols.extend(cols_t)
print('train_hids',len(train_hids))
X_train,Y_train=self.getXY(train_hids,labels,concat_cols)
# X_train (N, 62496 (nr F * T), concat: ethnicity, gender, insurance, ...): labels T = 72, F = 868
# columns: 225158_0 (feature_id_T)
# Y_train (N,): labels
# Saving X_train and Y_train as strongly compressed HDF5 files
start_time = time.time()
X_train.to_hdf(self.data_dt_folder + 'X_train.h5', key='X_train', mode='w', complevel=9, complib='blosc')
Y_train.to_hdf(self.data_dt_folder + 'Y_train.h5', key='Y_train', mode='w', complevel=9, complib='blosc')
save_time = time.time() - start_time
print(f"Time taken to save X_train & Y_train: {save_time} seconds")
start_time = time.time()
# Loading X_train and Y_train from HDF5 files
X_train = pd.read_hdf(self.data_dt_folder + 'X_train.h5', key='X_train')
Y_train = pd.read_hdf(self.data_dt_folder + 'Y_train.h5', key='Y_train')
save_time = time.time() - start_time
print(f"Time taken to load X_train & Y_train: {save_time} seconds")
#encoding categorical
gen_encoder = LabelEncoder()
eth_encoder = LabelEncoder()
ins_encoder = LabelEncoder()
age_encoder = LabelEncoder()
gen_encoder.fit(X_train['gender'])
eth_encoder.fit(X_train['ethnicity'])
ins_encoder.fit(X_train['insurance'])
#age_encoder.fit(X_train['Age'])
X_train['gender']=gen_encoder.transform(X_train['gender'])
X_train['ethnicity']=eth_encoder.transform(X_train['ethnicity'])
X_train['insurance']=ins_encoder.transform(X_train['insurance'])
#X_train['Age']=age_encoder.transform(X_train['Age'])
print(X_train.shape)
print(Y_train.shape)
print('test_hids',len(test_hids))
X_test,Y_test=self.getXY(test_hids,labels,concat_cols)
self.test_data=X_test.copy(deep=True)
X_test['gender']=gen_encoder.transform(X_test['gender'])
X_test['ethnicity']=eth_encoder.transform(X_test['ethnicity'])
X_test['insurance']=ins_encoder.transform(X_test['insurance'])
#X_test['Age']=age_encoder.transform(X_test['Age'])
print(X_test.shape)
print(Y_test.shape)
print("just before training")
print(X_test.head())
print(stop)
self.train_model(X_train,Y_train,X_test,Y_test)
def train_model(self,X_train,Y_train,X_test,Y_test):
#logits=[]
print("===============MODEL TRAINING===============")
if self.model_type=='Gradient Bossting':
model = HistGradientBoostingClassifier(categorical_features=[X_train.shape[1]-3,X_train.shape[1]-2,X_train.shape[1]-1]).fit(X_train, Y_train)
prob=model.predict_proba(X_test)
logits=np.log2(prob[:,1]/prob[:,0])
self.loss(prob[:,1],np.asarray(Y_test),logits,False,True)
self.save_output(Y_test,prob[:,1],logits)
elif self.model_type=='Logistic Regression':
X_train=pd.get_dummies(X_train,prefix=['gender','ethnicity','insurance'],columns=['gender','ethnicity','insurance'])
X_test=pd.get_dummies(X_test,prefix=['gender','ethnicity','insurance'],columns=['gender','ethnicity','insurance'])
model = LogisticRegression().fit(X_train, Y_train)
logits=model.predict_log_proba(X_test)
prob=model.predict_proba(X_test)
self.loss(prob[:,1],np.asarray(Y_test),logits[:,1],False,True)
self.save_outputImp(Y_test,prob[:,1],logits[:,1],model.coef_[0],X_train.columns)
elif self.model_type=='Random Forest':
X_train=pd.get_dummies(X_train,prefix=['gender','ethnicity','insurance'],columns=['gender','ethnicity','insurance'])
X_test=pd.get_dummies(X_test,prefix=['gender','ethnicity','insurance'],columns=['gender','ethnicity','insurance'])
model = RandomForestClassifier().fit(X_train, Y_train)
logits=model.predict_log_proba(X_test)
prob=model.predict_proba(X_test)
self.loss(prob[:,1],np.asarray(Y_test),logits[:,1],False,True)
self.save_outputImp(Y_test,prob[:,1],logits[:,1],model.feature_importances_,X_train.columns)
elif self.model_type=='Xgboost':
X_train=pd.get_dummies(X_train,prefix=['gender','ethnicity','insurance'],columns=['gender','ethnicity','insurance'])
X_test=pd.get_dummies(X_test,prefix=['gender','ethnicity','insurance'],columns=['gender','ethnicity','insurance'])
model = xgb.XGBClassifier(objective="binary:logistic").fit(X_train, Y_train)
#logits=model.predict_log_proba(X_test)
#print(self.test_data['ethnicity'])
#print(self.test_data.shape)
#print(self.test_data.head())
prob=model.predict_proba(X_test)
logits=np.log2(prob[:,1]/prob[:,0])
self.loss(prob[:,1],np.asarray(Y_test),logits,False,True)
self.save_outputImp(Y_test,prob[:,1],logits,model.feature_importances_,X_train.columns)
def getXY(self,ids,labels,concat_cols):
X_df=pd.DataFrame()
y_df=pd.DataFrame()
features=[]
print(ids)
print(len(ids))
for sample in tqdm(ids, desc="Processing samples"):
if self.data_icu:
y=labels[labels['stay_id']==sample]['label']
else:
y=labels[labels['hadm_id']==sample]['label']
#print(sample)
dyn=pd.read_csv('./data/csv/'+str(sample)+'/dynamic.csv',header=[0,1])
if self.concat:
dyn.columns=dyn.columns.droplevel(0)
dyn=dyn.to_numpy()
dyn=dyn.reshape(1,-1)
#print(dyn.shape)
#print(len(concat_cols))
dyn_df=pd.DataFrame(data=dyn,columns=concat_cols)
features=concat_cols
else:
dyn_df=pd.DataFrame()
#print(dyn)
for key in dyn.columns.levels[0]:
#print(sample)
dyn_temp=dyn[key]
if self.data_icu:
if ((key=="CHART") or (key=="MEDS")):
agg=dyn_temp.aggregate("mean")
agg=agg.reset_index()
else:
agg=dyn_temp.aggregate("max")
agg=agg.reset_index()
else:
if ((key=="LAB") or (key=="MEDS")):
agg=dyn_temp.aggregate("mean")
agg=agg.reset_index()
else:
agg=dyn_temp.aggregate("max")
agg=agg.reset_index()
if dyn_df.empty:
dyn_df=agg
else:
dyn_df=pd.concat([dyn_df,agg],axis=0)
#dyn_df=dyn_df.drop(index=(0))
# print(dyn_df.shape)
# print(dyn_df.head())
dyn_df=dyn_df.T
dyn_df.columns = dyn_df.iloc[0]
dyn_df=dyn_df.iloc[1:,:]
# print(dyn.shape)
# print(dyn_df.shape)
# print(dyn_df.head())
stat=pd.read_csv('./data/csv/'+str(sample)+'/static.csv',header=[0,1])
stat=stat['COND']
# print(stat.shape)
# print(stat.head())
demo=pd.read_csv('./data/csv/'+str(sample)+'/demo.csv',header=0)
# print(demo.shape)
# print(demo.head())
if X_df.empty:
X_df=pd.concat([dyn_df,stat],axis=1)
X_df=pd.concat([X_df,demo],axis=1)
else:
X_df=pd.concat([X_df,pd.concat([pd.concat([dyn_df,stat],axis=1),demo],axis=1)],axis=0)
if y_df.empty:
y_df=y
else:
y_df=pd.concat([y_df,y],axis=0)
# print("X_df",X_df.shape)
# print("y_df",y_df.shape)
print("X_df",X_df.shape)
print("y_df",y_df.shape)
return X_df ,y_df
def save_output(self,labels,prob,logits):
output_df=pd.DataFrame()
output_df['Labels']=labels.values
output_df['Prob']=prob
output_df['Logits']=np.asarray(logits)
output_df['ethnicity']=list(self.test_data['ethnicity'])
output_df['gender']=list(self.test_data['gender'])
output_df['age']=list(self.test_data['Age'])
output_df['insurance']=list(self.test_data['insurance'])
with open('./data/output/'+'outputDict', 'wb') as fp:
pickle.dump(output_df, fp)
def save_outputImp(self,labels,prob,logits,importance,features):
output_df=pd.DataFrame()
output_df['Labels']=labels.values
output_df['Prob']=prob
output_df['Logits']=np.asarray(logits)
output_df['ethnicity']=list(self.test_data['ethnicity'])
output_df['gender']=list(self.test_data['gender'])
output_df['age']=list(self.test_data['Age'])
output_df['insurance']=list(self.test_data['insurance'])
with open('./data/output/'+'outputDict', 'wb') as fp:
pickle.dump(output_df, fp)
imp_df=pd.DataFrame()
imp_df['imp']=importance
imp_df['feature']=features
imp_df.to_csv('./data/output/'+'feature_importance.csv', index=False)