thbndi commited on
Commit
58cd6d7
1 Parent(s): fb5888c

Delete Mimic4Dataset.py

Browse files
Files changed (1) hide show
  1. Mimic4Dataset.py +0 -1178
Mimic4Dataset.py DELETED
@@ -1,1178 +0,0 @@
1
- import os
2
- import pandas as pd
3
- import datasets
4
- import sys
5
- import pickle
6
- import subprocess
7
- import shutil
8
- from urllib.request import urlretrieve
9
- from sklearn.model_selection import train_test_split
10
- from sklearn.preprocessing import LabelEncoder
11
- import numpy as np
12
- from tqdm import tqdm
13
- import yaml
14
- import time
15
- import torch
16
-
17
-
18
- _DESCRIPTION = """\
19
- Dataset for mimic4 data, by default for the Mortality task.
20
- Available tasks are: Mortality, Length of Stay, Readmission, Phenotype.
21
- The data is extracted from the mimic4 database using this pipeline: 'https://github.com/healthylaife/MIMIC-IV-Data-Pipeline/tree/main'
22
- mimic path should have this form : "path/to/mimic4data/from/username/mimiciv/2.2"
23
- If you choose a Custom task provide a configuration file for the Time series.
24
- """
25
-
26
- _HOMEPAGE = "https://huggingface.co/datasets/thbndi/Mimic4Dataset"
27
- _CITATION = "https://proceedings.mlr.press/v193/gupta22a.html"
28
- _URL = "https://github.com/healthylaife/MIMIC-IV-Data-Pipeline"
29
- _DATA_GEN = 'https://huggingface.co/datasets/thbndi/Mimic4Dataset/resolve/main/data_generation_icu_modify.py'
30
- _DATA_GEN_HOSP= 'https://huggingface.co/datasets/thbndi/Mimic4Dataset/resolve/main/data_generation_modify.py'
31
- _DAY_INT= 'https://huggingface.co/datasets/thbndi/Mimic4Dataset/resolve/main/day_intervals_cohort_v22.py'
32
- _CONFIG_URLS = {'los' : 'https://huggingface.co/datasets/thbndi/Mimic4Dataset/resolve/main/config/los.config',
33
- 'mortality' : 'https://huggingface.co/datasets/thbndi/Mimic4Dataset/resolve/main/config/mortality.config',
34
- 'phenotype' : 'https://huggingface.co/datasets/thbndi/Mimic4Dataset/resolve/main/config/phenotype.config',
35
- 'readmission' : 'https://huggingface.co/datasets/thbndi/Mimic4Dataset/resolve/main/config/readmission.config'
36
- }
37
-
38
-
39
-
40
- def check_config(task,config_file):
41
- with open(config_file) as f:
42
- config = yaml.safe_load(f)
43
-
44
- if task=='Phenotype':
45
- disease_label = config['disease_label']
46
- else :
47
- disease_label = ""
48
- time = config['timePrediction']
49
- label = task
50
- timeW = config['timeWindow']
51
- include=int(timeW.split()[1])
52
- bucket = config['timebucket']
53
- radimp = config['radimp']
54
- predW = config['predW']
55
- disease_filter = config['disease_filter']
56
- icu_no_icu = config['icu_no_icu']
57
- groupingDiag = config['groupingDiag']
58
-
59
- assert( icu_no_icu in ['ICU','Non-ICU' ], "Chossen data should be one of the following: ICU, Non-ICU")
60
- data_icu = icu_no_icu=='ICU'
61
-
62
- if data_icu:
63
- chart_flag = config['chart']
64
- output_flag = config['output']
65
- select_chart = config['select_chart']
66
- lab_flag = False
67
- select_lab = False
68
- else:
69
- lab_flag =config['lab']
70
- select_lab = config['select_lab']
71
- groupingMed = config['groupingMed']
72
- groupingProc = config['groupingProc']
73
- chart_flag = False
74
- output_flag = False
75
- select_chart = False
76
-
77
-
78
- diag_flag= config['diagnosis']
79
- proc_flag = config['proc']
80
- meds_flag = config['meds']
81
- select_diag= config['select_diag']
82
- select_med= config['select_med']
83
- select_proc= config['select_proc']
84
- select_out = config['select_out']
85
-
86
- outlier_removal=config['outlier_removal']
87
- thresh=config['outlier']
88
- left_thresh=config['left_outlier']
89
-
90
- if data_icu:
91
- assert (isinstance(select_diag,bool) and isinstance(select_med,bool) and isinstance(select_proc,bool) and isinstance(select_out,bool) and isinstance(select_chart,bool), " select_diag, select_chart, select_med, select_proc, select_out should be boolean")
92
- assert (isinstance(chart_flag,bool) and isinstance(output_flag,bool) and isinstance(diag_flag,bool) and isinstance(proc_flag,bool) and isinstance(meds_flag,bool), "chart_flag, output_flag, diag_flag, proc_flag, meds_flag should be boolean")
93
-
94
- else:
95
- assert (isinstance(select_diag,bool) and isinstance(select_med,bool) and isinstance(select_proc,bool) and isinstance(select_out,bool) and isinstance(select_lab,bool), " select_diag, select_lab, select_med, select_proc, select_out should be boolean")
96
- assert (isinstance(lab_flag,bool) and isinstance(diag_flag,bool) and isinstance(proc_flag,bool) and isinstance(meds_flag,bool), "lab_flag, diag_flag, proc_flag, meds_flag should be boolean")
97
-
98
- if task=='Phenotype':
99
- if disease_label=='Heart Failure':
100
- label='Readmission'
101
- time=30
102
- disease_label='I50'
103
- elif disease_label=='CAD':
104
- label='Readmission'
105
- time=30
106
- disease_label='I25'
107
- elif disease_label=='CKD':
108
- label='Readmission'
109
- time=30
110
- disease_label='N18'
111
- elif disease_label=='COPD':
112
- label='Readmission'
113
- time=30
114
- disease_label='J44'
115
- else :
116
- raise ValueError('Disease label not correct provide one in the list: Heart Failure, CAD, CKD, COPD')
117
- predW=0
118
- assert (timeW[0]=='Last' and include<=72 and include>=24, "Time window should be between Last 24 and Last 72")
119
-
120
- elif task=='Mortality':
121
- time=0
122
- label= 'Mortality'
123
- assert (predW<=8 and predW>=2, "Prediction window should be between 2 and 8")
124
- assert (timeW[0]=='Fisrt' and include<=72 and include>=24, "Time window should be between First 24 and First 72")
125
-
126
- elif task=='Length_of_Stay':
127
- label= 'Length of Stay'
128
- assert (timeW[0]=='Fisrt' and include<=72 and include>=24, "Time window should be between Fisrt 24 and Fisrt 72")
129
- assert (time<=10 and time>=1, "Length of stay should be between 1 and 10")
130
- predW=0
131
-
132
- elif task=='Readmission':
133
- label= 'Readmission'
134
- assert (timeW[0]=='Last' and include<=72 and include>=24, "Time window should be between Last 24 and Last 72")
135
- assert (time<=150 and time>=10 and time%10==0, "Readmission window should be between 10 and 150 with a step of 10")
136
- predW=0
137
-
138
- else:
139
- raise ValueError('Task not correct')
140
-
141
- assert( disease_filter in ['Heart Failure','COPD','CKD','CAD',""], "Disease filter should be one of the following: Heart Failure, COPD, CKD, CAD or empty")
142
- assert( groupingDiag in ['Convert ICD-9 to ICD-10 and group ICD-10 codes','Keep both ICD-9 and ICD-10 codes','Convert ICD-9 to ICD-10 codes'], "Grouping ICD should be one of the following: Convert ICD-9 to ICD-10 and group ICD-10 codes, Keep both ICD-9 and ICD-10 codes, Convert ICD-9 to ICD-10 codes")
143
- assert (bucket<=6 and bucket>=1 and isinstance(bucket, int), "Time bucket should be between 1 and 6 and an integer")
144
- assert (radimp in ['No Imputation', 'forward fill and mean','forward fill and median'], "imputation should be one of the following: No Imputation, forward fill and mean, forward fill and median")
145
- if chart_flag:
146
- assert (left_thresh>=0 and left_thresh<=10 and isinstance(left_thresh, int), "Left outlier threshold should be between 0 and 10 and an integer")
147
- assert (thresh>=90 and thresh<=99 and isinstance(thresh, int), "Outlier threshold should be between 90 and 99 and an integer")
148
- assert (outlier_removal in ['No outlier detection','Impute Outlier (default:98)','Remove outliers (default:98)'], "Outlier removal should be one of the following: No outlier detection, Impute Outlier (default:98), Remove outliers (default:98)")
149
- if lab_flag:
150
- assert (left_thresh>=0 and left_thresh<=10 and isinstance(left_thresh, int), "Left outlier threshold should be between 0 and 10 and an integer")
151
- assert (thresh>=90 and thresh<=99 and isinstance(thresh, int), "Outlier threshold should be between 90 and 99 and an integer")
152
- assert (outlier_removal in ['No outlier detection','Impute Outlier (default:98)','Remove outliers (default:98)'], "Outlier removal should be one of the following: No outlier detection, Impute Outlier (default:98), Remove outliers (default:98)")
153
- assert (groupingProc in ['ICD-9 and ICD-10','ICD-10'], "Grouping procedure should be one of the following: ICD-9 and ICD-10, ICD-10")
154
- assert (groupingMed in ['Yes','No'], "Do you want to group Medication codes to use Non propietary names? : Grouping medication should be one of the following: Yes, No")
155
-
156
- return label, time, disease_label, predW
157
-
158
- def create_vocab(file,task):
159
- with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
160
- condVocab = pickle.load(fp)
161
- condVocabDict={}
162
- condVocabDict[0]=0
163
- for val in range(len(condVocab)):
164
- condVocabDict[condVocab[val]]= val+1
165
-
166
- return condVocabDict
167
-
168
- def gender_vocab():
169
- genderVocabDict={}
170
- genderVocabDict['<PAD>']=0
171
- genderVocabDict['M']=1
172
- genderVocabDict['F']=2
173
-
174
- return genderVocabDict
175
-
176
- def vocab(task,diag_flag,proc_flag,out_flag,chart_flag,med_flag,lab_flag):
177
- condVocabDict={}
178
- procVocabDict={}
179
- medVocabDict={}
180
- outVocabDict={}
181
- chartVocabDict={}
182
- labVocabDict={}
183
- ethVocabDict={}
184
- ageVocabDict={}
185
- genderVocabDict={}
186
- insVocabDict={}
187
-
188
- ethVocabDict=create_vocab('ethVocab',task)
189
- with open('./data/dict/'+task+'/ethVocabDict', 'wb') as fp:
190
- pickle.dump(ethVocabDict, fp)
191
-
192
- ageVocabDict=create_vocab('ageVocab',task)
193
- with open('./data/dict/'+task+'/ageVocabDict', 'wb') as fp:
194
- pickle.dump(ageVocabDict, fp)
195
-
196
- genderVocabDict=gender_vocab()
197
- with open('./data/dict/'+task+'/genderVocabDict', 'wb') as fp:
198
- pickle.dump(genderVocabDict, fp)
199
-
200
- insVocabDict=create_vocab('insVocab',task)
201
- with open('./data/dict/'+task+'/insVocabDict', 'wb') as fp:
202
- pickle.dump(insVocabDict, fp)
203
-
204
- if diag_flag:
205
- file='condVocab'
206
- with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
207
- condVocabDict = pickle.load(fp)
208
- if proc_flag:
209
- file='procVocab'
210
- with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
211
- procVocabDict = pickle.load(fp)
212
- if med_flag:
213
- file='medVocab'
214
- with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
215
- medVocabDict = pickle.load(fp)
216
- if out_flag:
217
- file='outVocab'
218
- with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
219
- outVocabDict = pickle.load(fp)
220
- if chart_flag:
221
- file='chartVocab'
222
- with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
223
- chartVocabDict = pickle.load(fp)
224
- if lab_flag:
225
- file='labsVocab'
226
- with open ('./data/dict/'+task+'/'+file, 'rb') as fp:
227
- labVocabDict = pickle.load(fp)
228
-
229
- return len(condVocabDict),len(procVocabDict),len(medVocabDict),len(outVocabDict),len(chartVocabDict),len(labVocabDict),ethVocabDict,genderVocabDict,ageVocabDict,insVocabDict
230
-
231
- def concat_data(data,task,feat_cond,feat_proc,feat_out,feat_chart,feat_meds,feat_lab):
232
- meds=data['Med']
233
- proc = data['Proc']
234
- out = data['Out']
235
- chart = data['Chart']
236
- cond= data['Cond']['fids']
237
-
238
- cond_df=pd.DataFrame()
239
- proc_df=pd.DataFrame()
240
- out_df=pd.DataFrame()
241
- chart_df=pd.DataFrame()
242
- meds_df=pd.DataFrame()
243
-
244
- #demographic
245
- demo=pd.DataFrame(columns=['Age','gender','ethnicity','label','insurance'])
246
- new_row = {'Age': data['age'], 'gender': data['gender'], 'ethnicity': data['ethnicity'], 'label': data['label'], 'insurance': data['insurance']}
247
- demo = demo.append(new_row, ignore_index=True)
248
-
249
- ##########COND#########
250
- if (feat_cond):
251
- #get all conds
252
- with open("./data/dict/"+task+"/condVocab", 'rb') as fp:
253
- conDict = pickle.load(fp)
254
- conds=pd.DataFrame(conDict,columns=['COND'])
255
- features=pd.DataFrame(np.zeros([1,len(conds)]),columns=conds['COND'])
256
-
257
- #onehot encode
258
- if(cond ==[]):
259
- cond_df=pd.DataFrame(np.zeros([1,len(features)]),columns=features['COND'])
260
- cond_df=cond_df.fillna(0)
261
- else:
262
- cond_df=pd.DataFrame(cond,columns=['COND'])
263
- cond_df['val']=1
264
- cond_df=(cond_df.drop_duplicates()).pivot(columns='COND',values='val').reset_index(drop=True)
265
- cond_df=cond_df.fillna(0)
266
- oneh = cond_df.sum().to_frame().T
267
- combined_df = pd.concat([features,oneh],ignore_index=True).fillna(0)
268
- combined_oneh=combined_df.sum().to_frame().T
269
- cond_df=combined_oneh
270
-
271
- ##########PROC#########
272
- if (feat_proc):
273
- with open("./data/dict/"+task+"/procVocab", 'rb') as fp:
274
- procDic = pickle.load(fp)
275
-
276
- if proc :
277
- feat=proc.keys()
278
- proc_val=[proc[key] for key in feat]
279
- procedures=pd.DataFrame(procDic,columns=['PROC'])
280
- features=pd.DataFrame(np.zeros([1,len(procedures)]),columns=procedures['PROC'])
281
- features.columns=pd.MultiIndex.from_product([["PROC"], features.columns])
282
- procs=pd.DataFrame(columns=feat)
283
- for p,v in zip(feat,proc_val):
284
- procs[p]=v
285
- procs.columns=pd.MultiIndex.from_product([["PROC"], procs.columns])
286
- proc_df = pd.concat([features,procs],ignore_index=True).fillna(0)
287
- else:
288
- procedures=pd.DataFrame(procDic,columns=['PROC'])
289
- features=pd.DataFrame(np.zeros([1,len(procedures)]),columns=procedures['PROC'])
290
- features.columns=pd.MultiIndex.from_product([["PROC"], features.columns])
291
- proc_df=features.fillna(0)
292
-
293
- ##########OUT#########
294
- if (feat_out):
295
- with open("./data/dict/"+task+"/outVocab", 'rb') as fp:
296
- outDic = pickle.load(fp)
297
-
298
- if out :
299
- feat=out.keys()
300
- out_val=[out[key] for key in feat]
301
- outputs=pd.DataFrame(outDic,columns=['OUT'])
302
- features=pd.DataFrame(np.zeros([1,len(outputs)]),columns=outputs['OUT'])
303
- features.columns=pd.MultiIndex.from_product([["OUT"], features.columns])
304
- outs=pd.DataFrame(columns=feat)
305
- for o,v in zip(feat,out_val):
306
- outs[o]=v
307
- outs.columns=pd.MultiIndex.from_product([["OUT"], outs.columns])
308
- out_df = pd.concat([features,outs],ignore_index=True).fillna(0)
309
- else:
310
- outputs=pd.DataFrame(outDic,columns=['OUT'])
311
- features=pd.DataFrame(np.zeros([1,len(outputs)]),columns=outputs['OUT'])
312
- features.columns=pd.MultiIndex.from_product([["OUT"], features.columns])
313
- out_df=features.fillna(0)
314
-
315
- ##########CHART#########
316
- if (feat_chart):
317
- with open("./data/dict/"+task+"/chartVocab", 'rb') as fp:
318
- chartDic = pickle.load(fp)
319
-
320
- if chart:
321
- charts=chart['val']
322
- feat=charts.keys()
323
- chart_val=[charts[key] for key in feat]
324
- charts=pd.DataFrame(chartDic,columns=['CHART'])
325
- features=pd.DataFrame(np.zeros([1,len(charts)]),columns=charts['CHART'])
326
- features.columns=pd.MultiIndex.from_product([["CHART"], features.columns])
327
-
328
- chart=pd.DataFrame(columns=feat)
329
- for c,v in zip(feat,chart_val):
330
- chart[c]=v
331
- chart.columns=pd.MultiIndex.from_product([["CHART"], chart.columns])
332
- chart_df = pd.concat([features,chart],ignore_index=True).fillna(0)
333
- else:
334
- charts=pd.DataFrame(chartDic,columns=['CHART'])
335
- features=pd.DataFrame(np.zeros([1,len(charts)]),columns=charts['CHART'])
336
- features.columns=pd.MultiIndex.from_product([["CHART"], features.columns])
337
- chart_df=features.fillna(0)
338
-
339
- ##########LAB#########
340
- if (feat_lab):
341
- with open("./data/dict/"+task+"/labsVocab", 'rb') as fp:
342
- chartDic = pickle.load(fp)
343
-
344
- if chart:
345
- charts=chart['val']
346
- feat=charts.keys()
347
- chart_val=[charts[key] for key in feat]
348
- charts=pd.DataFrame(chartDic,columns=['LAB'])
349
- features=pd.DataFrame(np.zeros([1,len(charts)]),columns=charts['LAB'])
350
- features.columns=pd.MultiIndex.from_product([["LAB"], features.columns])
351
-
352
- chart=pd.DataFrame(columns=feat)
353
- for c,v in zip(feat,chart_val):
354
- chart[c]=v
355
- chart.columns=pd.MultiIndex.from_product([["LAB"], chart.columns])
356
- chart_df = pd.concat([features,chart],ignore_index=True).fillna(0)
357
- else:
358
- charts=pd.DataFrame(chartDic,columns=['LAB'])
359
- features=pd.DataFrame(np.zeros([1,len(charts)]),columns=charts['LAB'])
360
- features.columns=pd.MultiIndex.from_product([["LAB"], features.columns])
361
- chart_df=features.fillna(0)
362
-
363
- ###MEDS
364
- if (feat_meds):
365
- with open("./data/dict/"+task+"/medVocab", 'rb') as fp:
366
- medDic = pickle.load(fp)
367
-
368
- if meds:
369
- feat=meds['signal'].keys()
370
- med_val=[meds['amount'][key] for key in feat]
371
- meds=pd.DataFrame(medDic,columns=['MEDS'])
372
- features=pd.DataFrame(np.zeros([1,len(meds)]),columns=meds['MEDS'])
373
- features.columns=pd.MultiIndex.from_product([["MEDS"], features.columns])
374
-
375
- med=pd.DataFrame(columns=feat)
376
- for m,v in zip(feat,med_val):
377
- med[m]=v
378
- med.columns=pd.MultiIndex.from_product([["MEDS"], med.columns])
379
- meds_df = pd.concat([features,med],ignore_index=True).fillna(0)
380
- else:
381
- meds=pd.DataFrame(medDic,columns=['MEDS'])
382
- features=pd.DataFrame(np.zeros([1,len(meds)]),columns=meds['MEDS'])
383
- features.columns=pd.MultiIndex.from_product([["MEDS"], features.columns])
384
- meds_df=features.fillna(0)
385
-
386
- dyn_df = pd.concat([meds_df,proc_df,out_df,chart_df], axis=1)
387
- return dyn_df,cond_df,demo
388
- def getXY_deep(data,task,feat_cond,feat_proc,feat_out,feat_chart,feat_meds,feat_lab):
389
- stat_df = torch.zeros(size=(1,0))
390
- demo_df = torch.zeros(size=(1,0))
391
- meds = torch.zeros(size=(0,0))
392
- charts = torch.zeros(size=(0,0))
393
- proc = torch.zeros(size=(0,0))
394
- out = torch.zeros(size=(0,0))
395
- lab = torch.zeros(size=(0,0))
396
- stat_df = torch.zeros(size=(1,0))
397
- demo_df = torch.zeros(size=(1,0))
398
-
399
- 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)
400
- dyn,cond_df,demo=concat_data(data,task.replace(" ","_"),feat_cond,feat_proc,feat_out,feat_chart,feat_meds,feat_lab)
401
-
402
- ###########""
403
- if feat_chart:
404
- charts = dyn['CHART']
405
- charts=charts.to_numpy()
406
- charts = torch.tensor(charts, dtype=torch.long)
407
- charts = charts.tolist()
408
-
409
- if feat_meds:
410
- meds = dyn['MEDS']
411
- meds=meds.to_numpy()
412
- meds = torch.tensor(meds, dtype=torch.long)
413
- meds = meds.tolist()
414
-
415
- if feat_proc:
416
- proc = dyn['PROC']
417
- proc=proc.to_numpy()
418
- proc = torch.tensor(proc, dtype=torch.long)
419
- proc = proc.tolist()
420
-
421
- if feat_out:
422
- out = dyn['OUT']
423
- out=out.to_numpy()
424
- out = torch.tensor(out, dtype=torch.long)
425
- out = out.tolist()
426
-
427
- if feat_lab:
428
- lab = dyn['LAB']
429
- lab=lab.to_numpy()
430
- lab = torch.tensor(lab, dtype=torch.long)
431
- lab = lab.tolist()
432
-
433
- ####################""
434
-
435
- stat=cond_df
436
- stat = stat.to_numpy()
437
- stat = torch.tensor(stat)
438
- if stat_df[0].nelement():
439
- stat_df = torch.cat((stat_df,stat),0)
440
- else:
441
- stat_df = stat
442
-
443
- y = int(demo['label'])
444
- demo["gender"].replace(gender_vocab, inplace=True)
445
- demo["ethnicity"].replace(eth_vocab, inplace=True)
446
- demo["insurance"].replace(ins_vocab, inplace=True)
447
- demo["Age"].replace(age_vocab, inplace=True)
448
- demo=demo[["gender","ethnicity","insurance","Age"]]
449
- demo = demo.values
450
- demo = torch.tensor(demo)
451
- if demo_df[0].nelement():
452
- demo_df = torch.cat((demo_df,demo),0)
453
- else:
454
- demo_df = demo
455
- stat_df = torch.tensor(stat_df)
456
- stat_df = stat_df.type(torch.LongTensor)
457
- stat_df = stat_df.squeeze()
458
- demo_df = torch.tensor(demo_df)
459
- demo_df = demo_df.type(torch.LongTensor)
460
- demo_df=demo_df.squeeze()
461
- y_df = torch.tensor(y)
462
- y_df = y_df.type(torch.LongTensor)
463
-
464
- return stat_df, demo_df, meds, charts, out, proc, lab, y
465
-
466
- def getXY(dyn,stat,demo,concat_cols,concat):
467
- X_df=pd.DataFrame()
468
- if concat:
469
- dyna=dyn.copy()
470
- dyna.columns=dyna.columns.droplevel(0)
471
- dyna=dyna.to_numpy()
472
- dyna=np.nan_to_num(dyna, copy=False)
473
- dyna=dyna.reshape(1,-1)
474
- dyn_df=pd.DataFrame(data=dyna,columns=concat_cols)
475
- else:
476
- dyn_df=pd.DataFrame()
477
- for key in dyn.columns.levels[0]:
478
- dyn_temp=dyn[key]
479
- if ((key=="CHART") or (key=="MEDS")):
480
- agg=dyn_temp.aggregate("mean")
481
- agg=agg.reset_index()
482
- else:
483
- agg=dyn_temp.aggregate("max")
484
- agg=agg.reset_index()
485
-
486
- if dyn_df.empty:
487
- dyn_df=agg
488
- else:
489
- dyn_df=pd.concat([dyn_df,agg],axis=0)
490
- dyn_df=dyn_df.T
491
- dyn_df.columns = dyn_df.iloc[0]
492
- dyn_df=dyn_df.iloc[1:,:]
493
-
494
- X_df=pd.concat([dyn_df,stat],axis=1)
495
- X_df=pd.concat([X_df,demo],axis=1)
496
- return X_df
497
-
498
-
499
-
500
-
501
-
502
-
503
- def task_cohort(task, mimic_path, config_path):
504
- sys.path.append('./preprocessing/day_intervals_preproc')
505
- sys.path.append('./utils')
506
- sys.path.append('./preprocessing/hosp_module_preproc')
507
- sys.path.append('./model')
508
- import day_intervals_cohort_v22
509
- import day_intervals_cohort
510
- import feature_selection_icu
511
- import data_generation_icu_modify
512
- import data_generation_modify
513
- import feature_selection_hosp
514
-
515
-
516
- root_dir = os.path.dirname(os.path.abspath('UserInterface.ipynb'))
517
- config_path='./config/'+config_path
518
- with open(config_path) as f:
519
- config = yaml.safe_load(f)
520
- version_path = mimic_path+'/'
521
- print(version_path)
522
- version = mimic_path.split('/')[-1][0]
523
- start = time.time()
524
- #----------------------------------------------config----------------------------------------------------
525
- label, tim, disease_label, predW = check_config(task,config_path)
526
- icu_no_icu = config['icu_no_icu']
527
- timeW = config['timeWindow']
528
- include=int(timeW.split()[1])
529
- bucket = config['timebucket']
530
- radimp = config['radimp']
531
-
532
- diag_flag = config['diagnosis']
533
- proc_flag= config['proc']
534
- med_flag = config['meds']
535
- disease_filter = config['disease_filter']
536
- groupingDiag = config['groupingDiag']
537
- select_diag= config['select_diag']
538
- select_med= config['select_med']
539
- select_proc= config['select_proc']
540
-
541
- if icu_no_icu=='ICU':
542
- out_flag = config['output']
543
- chart_flag = config['chart']
544
- select_out= config['select_out']
545
- select_chart= config['select_chart']
546
- lab_flag = False
547
- select_lab = False
548
- else:
549
- lab_flag = config['lab']
550
- groupingMed = config['groupingMed']
551
- groupingProc = config['groupingProc']
552
- select_lab= config['select_lab']
553
- out_flag = False
554
- chart_flag = False
555
- select_out= False
556
- select_chart= False
557
-
558
- # -------------------------------------------------------------------------------------------------------------
559
-
560
- data_icu=icu_no_icu=="ICU"
561
- data_mort=label=="Mortality"
562
- data_admn=label=='Readmission'
563
- data_los=label=='Length of Stay'
564
-
565
- if (disease_filter=="Heart Failure"):
566
- icd_code='I50'
567
- elif (disease_filter=="CKD"):
568
- icd_code='N18'
569
- elif (disease_filter=="COPD"):
570
- icd_code='J44'
571
- elif (disease_filter=="CAD"):
572
- icd_code='I25'
573
- else:
574
- icd_code='No Disease Filter'
575
-
576
- #-----------------------------------------------EXTRACT MIMIC-----------------------------------------------------
577
- if version == '2':
578
- cohort_output = day_intervals_cohort_v22.extract_data(icu_no_icu,label,tim,icd_code, root_dir,version_path,disease_label)
579
-
580
- elif version == '1':
581
- cohort_output = day_intervals_cohort.extract_data(icu_no_icu,label,tim,icd_code, root_dir,version_path,disease_label)
582
- #----------------------------------------------FEATURES-------------------------------------------------------
583
-
584
- if data_icu :
585
- feature_selection_icu.feature_icu(cohort_output, version_path,diag_flag,out_flag,chart_flag,proc_flag,med_flag)
586
- else:
587
- feature_selection_hosp.feature_nonicu(cohort_output, version_path,diag_flag,lab_flag,proc_flag,med_flag)
588
- #----------------------------------------------GROUPING-------------------------------------------------------
589
- if data_icu:
590
- if diag_flag:
591
- group_diag=groupingDiag
592
- feature_selection_icu.preprocess_features_icu(cohort_output, diag_flag, group_diag,False,False,False,0,0)
593
-
594
- else:
595
- if diag_flag:
596
- group_diag=groupingDiag
597
- if med_flag:
598
- group_med=groupingMed
599
- if proc_flag:
600
- group_proc=groupingProc
601
- feature_selection_hosp.preprocess_features_hosp(cohort_output, diag_flag,proc_flag,med_flag,False,group_diag,group_med,group_proc,False,False,0,0)
602
- #----------------------------------------------SUMMARY-------------------------------------------------------
603
- if data_icu:
604
- feature_selection_icu.generate_summary_icu(diag_flag,proc_flag,med_flag,out_flag,chart_flag)
605
- else:
606
- feature_selection_hosp.generate_summary_hosp(diag_flag,proc_flag,med_flag,lab_flag)
607
- #----------------------------------------------FEATURE SELECTION---------------------------------------------
608
-
609
- #----------------------------------------------FEATURE SELECTION---------------------------------------------
610
-
611
- if data_icu:
612
- if select_chart or select_out or select_diag or select_med or select_proc:
613
- if select_chart:
614
- input('Please edit list of codes in ./data/summary/chart_features.csv to select the chart items to keep and press enter to continue')
615
- if select_out:
616
- input('Please edit list of codes in ./data/summary/out_features.csv to select the output items to keep and press enter to continue')
617
- if select_diag:
618
- input('Please edit list of codes in ./data/summary/diag_features.csv to select the diagnosis ids to keep and press enter to continue')
619
- if select_med:
620
- input('Please edit list of codes in ./data/summary/med_features.csv to select the meds items to keep and press enter to continue')
621
- if select_proc:
622
- input('Please edit list of codes in ./data/summary/proc_features.csv to select the procedures ids to keep and press enter to continue')
623
- feature_selection_icu.features_selection_icu(cohort_output, diag_flag,proc_flag,med_flag,out_flag, chart_flag,select_diag,select_med,select_proc,select_out,select_chart)
624
- else:
625
- if select_diag or select_med or select_proc or select_lab:
626
- if select_diag:
627
- input('Please edit list of codes in ./data/summary/diag_features.csv to select the diagnosis ids to keep and press enter to continue')
628
- if select_med:
629
- input('Please edit list of codes in ./data/summary/med_features.csv to select the meds items to keep and press enter to continue')
630
- if select_proc:
631
- input('Please edit list of codes in ./data/summary/proc_features.csv to select the procedures ids to keep and press enter to continue')
632
- if select_lab:
633
- input('Please edit list of codes in ./data/summary/labs_features.csv to select the labs items to keep and press enter to continue')
634
- feature_selection_hosp.features_selection_hosp(cohort_output, diag_flag,proc_flag,med_flag,lab_flag,select_diag,select_med,select_proc,select_lab)
635
-
636
- #---------------------------------------CLEANING OF FEATURES-----------------------------------------------
637
- thresh=0
638
- if data_icu:
639
- if chart_flag:
640
- outlier_removal=config['outlier_removal']
641
- clean_chart=outlier_removal!='No outlier detection'
642
- impute_outlier_chart=outlier_removal=='Impute Outlier (default:98)'
643
- thresh=config['outlier']
644
- left_thresh=config['left_outlier']
645
- feature_selection_icu.preprocess_features_icu(cohort_output, False, False,chart_flag,clean_chart,impute_outlier_chart,thresh,left_thresh)
646
- else:
647
- if lab_flag:
648
- outlier_removal=config['outlier_removal']
649
- clean_chart=outlier_removal!='No outlier detection'
650
- impute_outlier_chart=outlier_removal=='Impute Outlier (default:98)'
651
- thresh=config['outlier']
652
- left_thresh=config['left_outlier']
653
- feature_selection_hosp.preprocess_features_hosp(cohort_output, False,False, False,lab_flag,False,False,False,clean_chart,impute_outlier_chart,thresh,left_thresh)
654
- # ---------------------------------------tim-Series Representation--------------------------------------------
655
- if radimp == 'forward fill and mean' :
656
- impute='Mean'
657
- elif radimp =='forward fill and median':
658
- impute = 'Median'
659
- else :
660
- impute = False
661
-
662
- if data_icu:
663
- gen=data_generation_icu_modify.Generator(task,cohort_output,data_mort,data_admn,data_los,diag_flag,proc_flag,out_flag,chart_flag,med_flag,impute,include,bucket,predW)
664
- else:
665
- gen=data_generation_modify.Generator(cohort_output,data_mort,data_admn,data_los,diag_flag,lab_flag,proc_flag,med_flag,impute,include,bucket,predW)
666
-
667
- end = time.time()
668
- print("Time elapsed : ", round((end - start)/60,2),"mins")
669
- print("[============TASK COHORT SUCCESSFULLY CREATED============]")
670
-
671
-
672
-
673
-
674
- #############################################DATASET####################################################################
675
- class Mimic4DatasetConfig(datasets.BuilderConfig):
676
- """BuilderConfig for Mimic4Dataset."""
677
-
678
- def __init__(
679
- self,
680
- **kwargs,
681
- ):
682
- super().__init__(**kwargs)
683
-
684
- class Mimic4Dataset(datasets.GeneratorBasedBuilder):
685
- VERSION = datasets.Version("1.0.0")
686
-
687
- def __init__(self, **kwargs):
688
- self.mimic_path = kwargs.pop("mimic_path", None)
689
- self.encoding = kwargs.pop("encoding",'raw')
690
- self.config_path = kwargs.pop("config_path",None)
691
- self.test_size = kwargs.pop("test_size",0.2)
692
- self.val_size = kwargs.pop("val_size",0.1)
693
- self.generate_cohort = kwargs.pop("generate_cohort",True)
694
-
695
- if self.encoding == 'concat':
696
- self.concat = True
697
- else:
698
- self.concat = False
699
-
700
- super().__init__(**kwargs)
701
-
702
-
703
- BUILDER_CONFIGS = [
704
- Mimic4DatasetConfig(
705
- name="Phenotype",
706
- version=VERSION,
707
- description="Dataset for mimic4 Phenotype task"
708
- ),
709
- Mimic4DatasetConfig(
710
- name="Readmission",
711
- version=VERSION,
712
- description="Dataset for mimic4 Readmission task"
713
- ),
714
- Mimic4DatasetConfig(
715
- name="Length of Stay",
716
- version=VERSION,
717
- description="Dataset for mimic4 Length of Stay task"
718
- ),
719
- Mimic4DatasetConfig(
720
- name="Mortality",
721
- version=VERSION,
722
- description="Dataset for mimic4 Mortality task"
723
- ),
724
- ]
725
-
726
- DEFAULT_CONFIG_NAME = "Mortality"
727
-
728
- def create_cohort(self):
729
- if self.config_path==None:
730
- if self.config.name == 'Phenotype' : self.config_path = _CONFIG_URLS['phenotype']
731
- if self.config.name == 'Readmission' : self.config_path = _CONFIG_URLS['readmission']
732
- if self.config.name == 'Length of Stay' : self.config_path = _CONFIG_URLS['los']
733
- if self.config.name == 'Mortality' : self.config_path = _CONFIG_URLS['mortality']
734
-
735
- version = self.mimic_path.split('/')[-1]
736
- mimic_folder= self.mimic_path.split('/')[-2]
737
- mimic_complete_path='/'+mimic_folder+'/'+version
738
-
739
- current_directory = os.getcwd()
740
- if os.path.exists(os.path.dirname(current_directory)+'/MIMIC-IV-Data-Pipeline-main'):
741
- dir =os.path.dirname(current_directory)
742
- os.chdir(dir)
743
- else:
744
- #move to parent directory of mimic data
745
- dir = self.mimic_path.replace(mimic_complete_path,'')
746
- if dir[-1]!='/':
747
- dir=dir+'/'
748
- elif dir=='':
749
- dir="./"
750
- parent_dir = os.path.dirname(self.mimic_path)
751
- os.chdir(parent_dir)
752
-
753
- #####################clone git repo if doesnt exists
754
- repo_url='https://github.com/healthylaife/MIMIC-IV-Data-Pipeline'
755
- if os.path.exists('MIMIC-IV-Data-Pipeline-main'):
756
- path_bench = './MIMIC-IV-Data-Pipeline-main'
757
- else:
758
- path_bench ='./MIMIC-IV-Data-Pipeline-main'
759
- subprocess.run(["git", "clone", repo_url, path_bench])
760
- os.makedirs(path_bench+'/mimic-iv')
761
- shutil.move(version,path_bench+'/mimic-iv')
762
-
763
- os.chdir(path_bench)
764
- self.mimic_path = './mimic-iv/'+version
765
-
766
- ####################Get configurations param
767
- #download config file if not custom
768
- if self.config_path[0:4] == 'http':
769
- c = self.config_path.split('/')[-1]
770
- file_path, head = urlretrieve(self.config_path,c)
771
- else :
772
- file_path = self.config_path
773
-
774
- if not os.path.exists('./config'):
775
- os.makedirs('config')
776
- #save config file in config folder
777
- self.conf='./config/'+file_path.split('/')[-1]
778
- if not os.path.exists(self.conf):
779
- shutil.move(file_path,'./config')
780
- with open(self.conf) as f:
781
- config = yaml.safe_load(f)
782
- timeW = config['timeWindow']
783
- self.timeW=int(timeW.split()[1])
784
- self.bucket = config['timebucket']
785
- self.data_icu = config['icu_no_icu']=='ICU'
786
- if self.data_icu:
787
- self.feat_cond, self.feat_chart, self.feat_proc, self.feat_meds, self.feat_out, self.lab = config['diagnosis'], config['chart'], config['proc'], config['meds'], config['output'], False
788
- self.feat_lab = False
789
- else:
790
- self.feat_cond, self.feat_lab, self.feat_proc, self.feat_meds, self.feat_chart, self.out = config['diagnosis'], config['lab'], config['proc'], config['meds'], False, False
791
- self.feat_out = False
792
- self.feat_chart = False
793
- #####################downloads modules from hub
794
- if not os.path.exists('./model/data_generation_icu_modify.py'):
795
- file_path, head = urlretrieve(_DATA_GEN, "data_generation_icu_modify.py")
796
- shutil.move(file_path, './model')
797
-
798
- if not os.path.exists('./model/data_generation_modify.py'):
799
- file_path, head = urlretrieve(_DATA_GEN_HOSP, "data_generation_modify.py")
800
- shutil.move(file_path, './model')
801
-
802
- if not os.path.exists('./preprocessing/day_intervals_preproc/day_intervals_cohort_v22.py'):
803
- file_path, head = urlretrieve(_DAY_INT, "day_intervals_cohort_v22.py")
804
- shutil.move(file_path, './preprocessing/day_intervals_preproc')
805
-
806
- data_dir = "./data/dict/"+self.config.name.replace(" ","_")+"/dataDic"
807
- sys.path.append(path_bench)
808
- config = self.config_path.split('/')[-1]
809
-
810
- #####################create task cohort
811
- if self.generate_cohort:
812
- task_cohort(self.config.name.replace(" ","_"),self.mimic_path,config)
813
-
814
- #####################Split data into train, test and val
815
- with open(data_dir, 'rb') as fp:
816
- dataDic = pickle.load(fp)
817
- data = pd.DataFrame.from_dict(dataDic)
818
-
819
- dict_dir = "./data/dict/"+self.config.name.replace(" ","_")
820
-
821
- data=data.T
822
- train_data, test_data = train_test_split(data, test_size=self.test_size, random_state=42)
823
- if self.val_size > 0 :
824
- train_data, val_data = train_test_split(train_data, test_size=self.val_size, random_state=42)
825
- val_dic = val_data.to_dict('index')
826
- val_path = dict_dir+'/val_data.pkl'
827
- with open(val_path, 'wb') as f:
828
- pickle.dump(val_dic, f)
829
-
830
- train_dic = train_data.to_dict('index')
831
- test_dic = test_data.to_dict('index')
832
-
833
- train_path = dict_dir+'/train_data.pkl'
834
- test_path = dict_dir+'/test_data.pkl'
835
-
836
-
837
- with open(train_path, 'wb') as f:
838
- pickle.dump(train_dic, f)
839
-
840
- with open(test_path, 'wb') as f:
841
- pickle.dump(test_dic, f)
842
-
843
- return dict_dir
844
-
845
- ###########################################################RAW##################################################################
846
-
847
- def _info_raw(self):
848
- features = datasets.Features(
849
- {
850
- "label": datasets.ClassLabel(num_classes=2,names=["0", "1"]),
851
- "gender": datasets.Value("string"),
852
- "ethnicity": datasets.Value("string"),
853
- "insurance": datasets.Value("string"),
854
- "age": datasets.Value("int32"),
855
- "COND": datasets.Sequence(datasets.Value("string")),
856
- "MEDS": {
857
- "signal":
858
- {
859
- "id": datasets.Sequence(datasets.Value("int32")),
860
- "value": datasets.Sequence(datasets.Sequence(datasets.Value("float32")))
861
- }
862
- ,
863
- "rate":
864
- {
865
- "id": datasets.Sequence(datasets.Value("int32")),
866
- "value": datasets.Sequence(datasets.Sequence(datasets.Value("float32")))
867
- }
868
- ,
869
- "amount":
870
- {
871
- "id": datasets.Sequence(datasets.Value("int32")),
872
- "value": datasets.Sequence(datasets.Sequence(datasets.Value("float32")))
873
- }
874
-
875
- },
876
- "PROC": {
877
- "id": datasets.Sequence(datasets.Value("int32")),
878
- "value": datasets.Sequence(datasets.Sequence(datasets.Value("float32")))
879
- },
880
- "CHART/LAB":
881
- {
882
- "signal" : {
883
- "id": datasets.Sequence(datasets.Value("int32")),
884
- "value": datasets.Sequence(datasets.Sequence(datasets.Value("float32")))
885
- },
886
- "val" : {
887
- "id": datasets.Sequence(datasets.Value("int32")),
888
- "value": datasets.Sequence(datasets.Sequence(datasets.Value("float32")))
889
- },
890
- },
891
- "OUT": {
892
- "id": datasets.Sequence(datasets.Value("int32")),
893
- "value": datasets.Sequence(datasets.Sequence(datasets.Value("float32")))
894
- },
895
-
896
- }
897
- )
898
- return datasets.DatasetInfo(
899
- description=_DESCRIPTION,
900
- features=features,
901
- homepage=_HOMEPAGE,
902
- citation=_CITATION,
903
- )
904
-
905
- def _generate_examples_raw(self, filepath):
906
- with open(filepath, 'rb') as fp:
907
- dataDic = pickle.load(fp)
908
- for hid, data in dataDic.items():
909
- proc_features = data['Proc']
910
- meds_features = data['Med']
911
- out_features = data['Out']
912
- cond_features = data['Cond']['fids']
913
- eth= data['ethnicity']
914
- age = data['age']
915
- gender = data['gender']
916
- label = data['label']
917
- insurance=data['insurance']
918
-
919
- items = list(proc_features.keys())
920
- values =[proc_features[i] for i in items ]
921
- procs = {"id" : items,
922
- "value": values}
923
-
924
- items_outs = list(out_features.keys())
925
- values_outs =[out_features[i] for i in items_outs ]
926
- outs = {"id" : items_outs,
927
- "value": values_outs}
928
-
929
- if self.data_icu:
930
- chart_features = data['Chart']
931
- else:
932
- chart_features = data['Lab']
933
-
934
- #chart signal
935
- if ('signal' in chart_features):
936
- items_chart_sig = list(chart_features['signal'].keys())
937
- values_chart_sig =[chart_features['signal'][i] for i in items_chart_sig ]
938
- chart_sig = {"id" : items_chart_sig,
939
- "value": values_chart_sig}
940
- else:
941
- chart_sig = {"id" : [],
942
- "value": []}
943
- #chart val
944
- if ('val' in chart_features):
945
- items_chart_val = list(chart_features['val'].keys())
946
- values_chart_val =[chart_features['val'][i] for i in items_chart_val ]
947
- chart_val = {"id" : items_chart_val,
948
- "value": values_chart_val}
949
- else:
950
- chart_val = {"id" : [],
951
- "value": []}
952
-
953
- charts = {"signal" : chart_sig,
954
- "val" : chart_val}
955
-
956
- #meds signal
957
- if ('signal' in meds_features):
958
- items_meds_sig = list(meds_features['signal'].keys())
959
- values_meds_sig =[meds_features['signal'][i] for i in items_meds_sig ]
960
- meds_sig = {"id" : items_meds_sig,
961
- "value": values_meds_sig}
962
- else:
963
- meds_sig = {"id" : [],
964
- "value": []}
965
- #meds rate
966
- if ('rate' in meds_features):
967
- items_meds_rate = list(meds_features['rate'].keys())
968
- values_meds_rate =[meds_features['rate'][i] for i in items_meds_rate ]
969
- meds_rate = {"id" : items_meds_rate,
970
- "value": values_meds_rate}
971
- else:
972
- meds_rate = {"id" : [],
973
- "value": []}
974
- #meds amount
975
- if ('amount' in meds_features):
976
- items_meds_amount = list(meds_features['amount'].keys())
977
- values_meds_amount =[meds_features['amount'][i] for i in items_meds_amount ]
978
- meds_amount = {"id" : items_meds_amount,
979
- "value": values_meds_amount}
980
- else:
981
- meds_amount = {"id" : [],
982
- "value": []}
983
-
984
- meds = {"signal" : meds_sig,
985
- "rate" : meds_rate,
986
- "amount" : meds_amount}
987
-
988
-
989
- yield int(hid), {
990
- "label" : label,
991
- "gender" : gender,
992
- "ethnicity" : eth,
993
- "insurance" : insurance,
994
- "age" : age,
995
- "COND" : cond_features,
996
- "PROC" : procs,
997
- "CHART/LAB" : charts,
998
- "OUT" : outs,
999
- "MEDS" : meds
1000
- }
1001
-
1002
-
1003
-
1004
- ###########################################################ENCODED##################################################################
1005
-
1006
- def _info_encoded(self):
1007
- features = datasets.Features(
1008
- {
1009
- "label": datasets.ClassLabel(num_classes=2,names=["0", "1"]),
1010
- "features" : datasets.Sequence(datasets.Value("float32")),
1011
- }
1012
- )
1013
- return datasets.DatasetInfo(
1014
- description=_DESCRIPTION,
1015
- features=features,
1016
- homepage=_HOMEPAGE,
1017
- citation=_CITATION,
1018
- )
1019
-
1020
- def _generate_examples_encoded(self, filepath):
1021
- path= './data/dict/'+self.config.name.replace(" ","_")+'/ethVocab'
1022
- with open(path, 'rb') as fp:
1023
- ethVocab = pickle.load(fp)
1024
-
1025
- path= './data/dict/'+self.config.name.replace(" ","_")+'/insVocab'
1026
- with open(path, 'rb') as fp:
1027
- insVocab = pickle.load(fp)
1028
-
1029
- genVocab = ['<PAD>', 'M', 'F']
1030
- gen_encoder = LabelEncoder()
1031
- eth_encoder = LabelEncoder()
1032
- ins_encoder = LabelEncoder()
1033
- gen_encoder.fit(genVocab)
1034
- eth_encoder.fit(ethVocab)
1035
- ins_encoder.fit(insVocab)
1036
- with open(filepath, 'rb') as fp:
1037
- dico = pickle.load(fp)
1038
-
1039
- df = pd.DataFrame.from_dict(dico, orient='index')
1040
- task=self.config.name.replace(" ","_")
1041
-
1042
- for i, data in df.iterrows():
1043
- concat_cols=[]
1044
- dyn_df,cond_df,demo=concat_data(data,task,self.feat_cond,self.feat_proc,self.feat_out, self.feat_chart, self.feat_meds,self.feat_lab)
1045
- dyn=dyn_df.copy()
1046
- dyn.columns=dyn.columns.droplevel(0)
1047
- cols=dyn.columns
1048
- time=dyn.shape[0]
1049
- for t in range(time):
1050
- cols_t = [str(x) + "_"+str(t) for x in cols]
1051
- concat_cols.extend(cols_t)
1052
- demo['gender']=gen_encoder.transform(demo['gender'])
1053
- demo['ethnicity']=eth_encoder.transform(demo['ethnicity'])
1054
- demo['insurance']=ins_encoder.transform(demo['insurance'])
1055
- label = data['label']
1056
- demo=demo.drop(['label'],axis=1)
1057
- X= getXY(dyn_df,cond_df,demo,concat_cols,self.concat)
1058
- X=X.values.tolist()[0]
1059
- yield int(i), {
1060
- "label": label,
1061
- "features": X,
1062
- }
1063
- ######################################################DEEP###############################################################
1064
- def _info_deep(self):
1065
- features = datasets.Features(
1066
- {
1067
- "label": datasets.ClassLabel(num_classes=2,names=["0", "1"]),
1068
- #"DEMO": datasets.Array2D(shape=(None, 4), dtype='int64') ,
1069
- "DEMO": datasets.Sequence(datasets.Value("int64")),
1070
- "COND" : datasets.Sequence(datasets.Value("int64")),
1071
- #"COND" : datasets.Array2D(shape=(None, self.size_cond), dtype='int64') ,
1072
- "MEDS" : datasets.Array2D(shape=(None, self.size_meds), dtype='int64') ,
1073
- "PROC" : datasets.Array2D(shape=(None, self.size_proc), dtype='int64') ,
1074
- "CHART/LAB" : datasets.Array2D(shape=(None, self.size_chart), dtype='int64') ,
1075
- #"CHART/LAB" : datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
1076
- "OUT" : datasets.Array2D(shape=(None, self.size_out), dtype='int64') ,
1077
-
1078
- }
1079
- )
1080
- return datasets.DatasetInfo(
1081
- description=_DESCRIPTION,
1082
- features=features,
1083
- homepage=_HOMEPAGE,
1084
- citation=_CITATION,
1085
- )
1086
-
1087
-
1088
- def _generate_examples_deep(self, filepath):
1089
- with open(filepath, 'rb') as fp:
1090
- dico = pickle.load(fp)
1091
- task=self.config.name.replace(" ","_")
1092
- for key, data in dico.items():
1093
- stat, demo, meds, chart, out, proc, lab, y = getXY_deep(data, task, self.feat_cond, self.feat_proc, self.feat_out, self.feat_chart, self.feat_meds,self.feat_lab)
1094
-
1095
- verri=True
1096
- if self.feat_proc:
1097
- if (len(proc)<(self.timeW//self.bucket)):
1098
- verri=False
1099
- if self.feat_out:
1100
- if (len(out)<(self.timeW//self.bucket)):
1101
- verri=False
1102
- if self.feat_chart:
1103
- if (len(chart)<(self.timeW//self.bucket)):
1104
- verri=False
1105
- if self.feat_meds:
1106
- if (len(meds)<(self.timeW//self.bucket)):
1107
- verri=False
1108
- if self.feat_lab:
1109
- if (len(lab)<(self.timeW//self.bucket)):
1110
- verri=False
1111
- if verri:
1112
- if self.data_icu:
1113
- yield int(key), {
1114
- 'label': y,
1115
- 'DEMO': demo,
1116
- 'COND': stat,
1117
- 'MEDS': meds,
1118
- 'PROC': proc,
1119
- 'CHART/LAB': chart,
1120
- 'OUT': out,
1121
- }
1122
- else:
1123
- yield int(key), {
1124
- 'label': y,
1125
- 'DEMO': demo,
1126
- 'COND': stat,
1127
- 'MEDS': meds,
1128
- 'PROC': proc,
1129
- 'CHART/LAB': lab,
1130
- 'OUT': out,
1131
- }
1132
- else:
1133
- continue
1134
-
1135
-
1136
- #############################################################################################################################
1137
- def _info(self):
1138
- self.path = self.create_cohort()
1139
- self.size_cond, self.size_proc, self.size_meds, self.size_out, self.size_chart, self.size_lab, eth_vocab,gender_vocab,age_vocab,ins_vocab=vocab(self.config.name.replace(" ","_"),self.feat_cond,self.feat_proc,self.feat_out,self.feat_chart,self.feat_meds,self.feat_lab)
1140
-
1141
- if self.encoding == 'concat' :
1142
- return self._info_encoded()
1143
-
1144
- elif self.encoding == 'aggreg' :
1145
- return self._info_encoded()
1146
-
1147
- elif self.encoding == 'tensor' :
1148
- return self._info_deep()
1149
-
1150
- else:
1151
- return self._info_raw()
1152
-
1153
-
1154
- def _split_generators(self, dl_manager):
1155
- csv_dir = "./data/dict/"+self.config.name.replace(" ","_")
1156
- if self.val_size > 0 :
1157
- return [
1158
- datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": csv_dir+'/train_data.pkl'}),
1159
- datasets.SplitGenerator(name=datasets.Split.VALIDATION, gen_kwargs={"filepath": csv_dir+'/val_data.pkl'}),
1160
- datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": csv_dir+'/test_data.pkl'}),
1161
- ]
1162
- else :
1163
- return [
1164
- datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": csv_dir+'/train_data.pkl'}),
1165
- datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": csv_dir+'/test_data.pkl'}),
1166
- ]
1167
- def _generate_examples(self, filepath):
1168
-
1169
- if self.encoding == 'concat' :
1170
- yield from self._generate_examples_encoded(filepath)
1171
-
1172
- elif self.encoding == 'aggreg' :
1173
- yield from self._generate_examples_encoded(filepath)
1174
-
1175
- elif self.encoding == 'tensor' :
1176
- yield from self._generate_examples_deep(filepath)
1177
- else :
1178
- yield from self._generate_examples_raw(filepath)