File size: 15,078 Bytes
cb07198 cad1204 cb07198 cad1204 cb07198 30fa87d cb07198 cad1204 cb07198 8dd3b3b fec120c 8dd3b3b cb07198 cad1204 cb07198 cad1204 cb07198 8dd3b3b 010d1e0 8dd3b3b cb07198 cad1204 cb07198 cad1204 cb07198 8dd3b3b 69d3221 8dd3b3b cb07198 cad1204 cb07198 cad1204 cb07198 cad1204 cb07198 8dd3b3b cb07198 fec120c 8dd3b3b cb07198 cad1204 cb07198 dd7c0c8 cb07198 cad1204 cb07198 8dd3b3b fec120c 8dd3b3b cb07198 cad1204 cb07198 cad1204 88cbab5 8496698 cb07198 cad1204 cb07198 6548ca8 9266bf8 cb07198 88cbab5 cb07198 9266bf8 cb07198 9266bf8 cb07198 9266bf8 cb07198 2e8d614 24816db 9266bf8 cb07198 2e8d614 cb07198 991fed0 9266bf8 6548ca8 cb07198 5ff6ba1 46d884d 5ff6ba1 |
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 |
import pandas as pd
import pickle
import numpy as np
import torch
def create_vocab(file,task):
with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
condVocab = pickle.load(fp)
condVocabDict={}
condVocabDict[0]=0
for val in range(len(condVocab)):
condVocabDict[condVocab[val]]= val+1
return condVocabDict
def gender_vocab():
genderVocabDict={}
genderVocabDict['<PAD>']=0
genderVocabDict['M']=1
genderVocabDict['F']=2
return genderVocabDict
def vocab(task,diag_flag,proc_flag,out_flag,chart_flag,med_flag,lab_flag):
condVocabDict={}
procVocabDict={}
medVocabDict={}
outVocabDict={}
chartVocabDict={}
labVocabDict={}
ethVocabDict={}
ageVocabDict={}
genderVocabDict={}
insVocabDict={}
ethVocabDict=create_vocab('ethVocab',task)
with open('./data/dict/'+task+'/ethVocabDict', 'wb') as fp:
pickle.dump(ethVocabDict, fp)
ageVocabDict=create_vocab('ageVocab',task)
with open('./data/dict/'+task+'/ageVocabDict', 'wb') as fp:
pickle.dump(ageVocabDict, fp)
genderVocabDict=gender_vocab()
with open('./data/dict/'+task+'/genderVocabDict', 'wb') as fp:
pickle.dump(genderVocabDict, fp)
insVocabDict=create_vocab('insVocab',task)
with open('./data/dict/'+task+'/insVocabDict', 'wb') as fp:
pickle.dump(insVocabDict, fp)
if diag_flag:
file='condVocab'
with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
condVocabDict = pickle.load(fp)
if proc_flag:
file='procVocab'
with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
procVocabDict = pickle.load(fp)
if med_flag:
file='medVocab'
with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
medVocabDict = pickle.load(fp)
if out_flag:
file='outVocab'
with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
outVocabDict = pickle.load(fp)
if chart_flag:
file='chartVocab'
with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
chartVocabDict = pickle.load(fp)
if lab_flag:
file='labsVocab'
with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
labVocabDict = pickle.load(fp)
return len(condVocabDict),len(procVocabDict),len(medVocabDict),len(outVocabDict),len(chartVocabDict),len(labVocabDict),ethVocabDict,genderVocabDict,ageVocabDict,insVocabDict
def open_dict(task,cond, proc, out, chart, lab, med):
if cond:
with open("./data/dict/"+task+"/condVocab", 'rb') as fp:
condDict = pickle.load(fp)
else:
condDict = None
if proc:
with open("./data/dict/"+task+"/procVocab", 'rb') as fp:
procDict = pickle.load(fp)
else:
procDict = None
if out:
with open("./data/dict/"+task+"/outVocab", 'rb') as fp:
outDict = pickle.load(fp)
else:
outDict = None
if chart:
with open("./data/dict/"+task+"/chartVocab", 'rb') as fp:
chartDict = pickle.load(fp)
elif lab:
with open("./data/dict/"+task+"/labsVocab", 'rb') as fp:
chartDict = pickle.load(fp)
else:
chartDict = None
if med:
with open("./data/dict/"+task+"/medVocab", 'rb') as fp:
medDict = pickle.load(fp)
else:
medDict = None
return condDict, procDict, outDict, chartDict, medDict
def concat_data(data,task,feat_cond,feat_proc,feat_out,feat_chart,feat_meds,feat_lab,condDict, procDict, outDict, chartDict, medDict):
meds=data['Med']
proc = data['Proc']
out = data['Out']
chart = data['Chart']
cond= data['Cond']['fids']
cond_df=pd.DataFrame()
proc_df=pd.DataFrame()
out_df=pd.DataFrame()
chart_df=pd.DataFrame()
meds_df=pd.DataFrame()
#demographic
demo=pd.DataFrame(columns=['Age','gender','ethnicity','label','insurance'])
new_row = {'Age': data['age'], 'gender': data['gender'], 'ethnicity': data['ethnicity'], 'label': data['label'], 'insurance': data['insurance']}
demo = demo.append(new_row, ignore_index=True)
##########COND#########
if (feat_cond):
conds=pd.DataFrame(condDict,columns=['COND'])
features=pd.DataFrame(np.zeros([1,len(conds)]),columns=conds['COND'])
#onehot encode
if(cond ==[]):
cond_df=pd.DataFrame(np.zeros([1,len(features)]),columns=features['COND'])
cond_df=cond_df.fillna(0)
else:
cond_df=pd.DataFrame(cond,columns=['COND'])
cond_df['val']=1
cond_df=(cond_df.drop_duplicates()).pivot(columns='COND',values='val').reset_index(drop=True)
cond_df=cond_df.fillna(0)
oneh = cond_df.sum().to_frame().T
combined_df = pd.concat([features,oneh],ignore_index=True).fillna(0)
combined_oneh=combined_df.sum().to_frame().T
cond_df=combined_oneh
for c in cond_df.columns :
if c not in features:
cond_df=cond_df.drop(columns=[c])
##########PROC#########
if (feat_proc):
if proc :
feat=proc.keys()
proc_val=[proc[key] for key in feat]
procedures=pd.DataFrame(procDict,columns=['PROC'])
features=pd.DataFrame(np.zeros([1,len(procedures)]),columns=procedures['PROC'])
procs=pd.DataFrame(columns=feat)
for p,v in zip(feat,proc_val):
procs[p]=v
features=features.drop(columns=procs.columns.to_list())
proc_df = pd.concat([features,procs],axis=1).fillna(0)
proc_df.columns=pd.MultiIndex.from_product([["PROC"], proc_df.columns])
else:
procedures=pd.DataFrame(procDict,columns=['PROC'])
features=pd.DataFrame(np.zeros([1,len(procedures)]),columns=procedures['PROC'])
features.columns=pd.MultiIndex.from_product([["PROC"], features.columns])
proc_df=features.fillna(0)
##########OUT#########
if (feat_out):
if out :
feat=out.keys()
out_val=[out[key] for key in feat]
outputs=pd.DataFrame(outDict,columns=['OUT'])
features=pd.DataFrame(np.zeros([1,len(outputs)]),columns=outputs['OUT'])
outs=pd.DataFrame(columns=feat)
for o,v in zip(feat,out_val):
outs[o]=v
features=features.drop(columns=outs.columns.to_list())
out_df = pd.concat([features,outs],axis=1).fillna(0)
out_df.columns=pd.MultiIndex.from_product([["OUT"], out_df.columns])
else:
outputs=pd.DataFrame(outDict,columns=['OUT'])
features=pd.DataFrame(np.zeros([1,len(outputs)]),columns=outputs['OUT'])
features.columns=pd.MultiIndex.from_product([["OUT"], features.columns])
out_df=features.fillna(0)
##########CHART#########
if (feat_chart):
if chart:
charts=chart['val']
feat=charts.keys()
chart_val=[charts[key] for key in feat]
charts=pd.DataFrame(chartDict,columns=['CHART'])
features=pd.DataFrame(np.zeros([1,len(charts)]),columns=charts['CHART'])
chart=pd.DataFrame(columns=feat)
for c,v in zip(feat,chart_val):
chart[c]=v
features=features.drop(columns=chart.columns.to_list())
chart_df = pd.concat([features,chart],axis=1).fillna(0)
chart_df.columns=pd.MultiIndex.from_product([["CHART"], chart_df.columns])
else:
charts=pd.DataFrame(chartDict,columns=['CHART'])
features=pd.DataFrame(np.zeros([1,len(charts)]),columns=charts['CHART'])
features.columns=pd.MultiIndex.from_product([["CHART"], features.columns])
chart_df=features.fillna(0)
##########LAB#########
if (feat_lab):
if chart:
charts=chart['val']
feat=charts.keys()
chart_val=[charts[key] for key in feat]
charts=pd.DataFrame(chartDict,columns=['LAB'])
features=pd.DataFrame(np.zeros([1,len(charts)]),columns=charts['LAB'])
chart=pd.DataFrame(columns=feat)
for c,v in zip(feat,chart_val):
chart[c]=v
features=features.drop(columns=chart.columns.to_list())
chart.columns=pd.MultiIndex.from_product([["LAB"], chart.columns])
chart_df = pd.concat([features,chart],axis=1).fillna(0)
chart_df.columns=pd.MultiIndex.from_product([["LAB"], chart_df.columns])
else:
charts=pd.DataFrame(chartDict,columns=['LAB'])
features=pd.DataFrame(np.zeros([1,len(charts)]),columns=charts['LAB'])
features.columns=pd.MultiIndex.from_product([["LAB"], features.columns])
chart_df=features.fillna(0)
###MEDS
if (feat_meds):
if meds:
feat=meds['signal'].keys()
med_val=[meds['amount'][key] for key in feat]
meds=pd.DataFrame(medDict,columns=['MEDS'])
features=pd.DataFrame(np.zeros([1,len(meds)]),columns=meds['MEDS'])
med=pd.DataFrame(columns=feat)
for m,v in zip(feat,med_val):
med[m]=v
features=features.drop(columns=med.columns.to_list())
meds_df = pd.concat([features,med],axis=1).fillna(0)
meds_df.columns=pd.MultiIndex.from_product([["MEDS"], meds_df.columns])
else:
meds=pd.DataFrame(medDict,columns=['MEDS'])
features=pd.DataFrame(np.zeros([1,len(meds)]),columns=meds['MEDS'])
features.columns=pd.MultiIndex.from_product([["MEDS"], features.columns])
meds_df=features.fillna(0)
dyn_df = pd.concat([meds_df,proc_df,out_df,chart_df], axis=1)
return dyn_df,cond_df,demo
def generate_deep(data,task,feat_cond,feat_proc,feat_out,feat_chart,feat_meds,feat_lab,condDict, procDict, outDict, chartDict, medDict):
meds = []
charts = []
proc = []
out = []
lab = []
stat = []
demo = []
size_cond, size_proc, size_meds, size_out, size_chart, size_lab, eth_vocab,gender_vocab,age_vocab,ins_vocab=vocab(task.replace(" ","_"),feat_cond,feat_proc,feat_out,feat_chart,feat_meds,False)
dyn,cond_df,demo=concat_data(data,task.replace(" ","_"),feat_cond,feat_proc,feat_out,feat_chart,feat_meds,feat_lab,condDict, procDict, outDict, chartDict, medDict)
if feat_chart:
charts = dyn['CHART'].values
if feat_meds:
meds = dyn['MEDS'].values
if feat_proc:
proc = dyn['PROC'].values
if feat_out:
out = dyn['OUT'].values
if feat_lab:
lab = dyn['LAB'].values
if feat_cond:
stat=cond_df.values[0]
y = int(demo['label'])
demo["gender"].replace(gender_vocab, inplace=True)
demo["ethnicity"].replace(eth_vocab, inplace=True)
demo["insurance"].replace(ins_vocab, inplace=True)
demo["Age"].replace(age_vocab, inplace=True)
demo=demo[["gender","ethnicity","insurance","Age"]]
demo = demo.values[0]
return stat, demo, meds, charts, out, proc, lab, y
def generate_ml(dyn,stat,demo,concat_cols,concat):
X_df=pd.DataFrame()
if concat:
dyna=dyn.copy()
dyna.columns=dyna.columns.droplevel(0)
dyna=dyna.to_numpy()
dyna=np.nan_to_num(dyna, copy=False)
dyna=dyna.reshape(1,-1)
dyn_df=pd.DataFrame(data=dyna,columns=concat_cols)
else:
dyn_df=pd.DataFrame()
for key in dyn.columns.levels[0]:
dyn_temp=dyn[key]
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()
if dyn_df.empty:
dyn_df=agg
else:
dyn_df=pd.concat([dyn_df,agg],axis=0)
dyn_df=dyn_df.T
dyn_df.columns = dyn_df.iloc[0]
dyn_df=dyn_df.iloc[1:,:]
X_df=pd.concat([dyn_df,stat],axis=1)
X_df=pd.concat([X_df,demo],axis=1)
return X_df
def generate_text(data,icd,items,feat_cond,feat_chart,feat_meds, feat_proc, feat_out):
#Diagnosis
if feat_cond:
conds = data['Cond']['fids']
cond_text=[]
for code in conds:
desc = icd[icd['code']==code]
if not desc.empty:
cond_text.append(desc['description'].to_string(index=False))
template = 'The patient is diagnosed with {}.'
cond_text = template.format(';'.join(cond_text))
else :
cond_text=''
#chart
if feat_chart:
chart = data['Chart']
if chart:
charts=chart['val']
feat=charts.keys()
chart_val=[charts[key] for key in feat]
chart_mean = [round(np.mean(c),3) for c in chart_val]
feat_text = [(items[items['itemid']==f]['label']).to_string(index=False) for f in feat]
template='{} for {}'
chart_text = []
for mean_val, feat_label in zip(chart_mean, feat_text):
text = template.format(mean_val,feat_label)
chart_text.append(text)
chart_text='The chart events mesured are :{}.' + ';'.join(chart_text)
else:
chart_text=''
#meds
if feat_meds:
meds = data['Med']
if meds:
feat=meds['signal'].keys()
meds_val=[meds['amount'][key] for key in feat]
meds_mean = [round(np.mean(c),3) for c in meds_val]
feat_text = [(items[items['itemid']==f]['label']).to_string(index=False) for f in feat]
template='{} of {}'
meds_text = []
for mean_val, feat_label in zip(meds_mean, feat_text):
text = template.format(mean_val,feat_label)
meds_text.append(text)
meds_text='The mean amounts of medications administered during the episode are :{}.' + ';'.join(meds_text)
else:
meds_text=''
#proc
if feat_proc:
proc = data['Proc']
if proc:
feat=proc.keys()
feat_text = [(items[items['itemid']==f]['label']).to_string(index=False) for f in feat]
proc_text='The procedures performed are :{}.' + ';'.join(feat_text)
else:
proc_text=''
#out
if feat_out:
out = data['Out']
if out:
feat=out.keys()
feat_text = [(items[items['itemid']==f]['label']).to_string(index=False) for f in feat]
out_text='The outputs collected are :{}.' + ';'.join(feat_text)
else:
out_text=''
return cond_text,chart_text,meds_text,proc_text,out_text
|