-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexperiments.py
3749 lines (2846 loc) · 170 KB
/
experiments.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
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
# In[1]:
"""
Name:AUC_GH.py
Description: Train models on mimic-iii data with knowledge of the years
Author(s): Bret Nestor
Date: Written Sept.6, 2018
Licence:
"""
print("start")
import sys
import pandas as pd
import numpy as np
import os
import pathlib
from sklearn.svm import SVC, LinearSVC, OneClassSVM
from sklearn.neural_network import MLPClassifier
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import Lasso, LinearRegression, LogisticRegression, LassoCV, LogisticRegressionCV
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor, IsolationForest
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import RandomizedSearchCV, GridSearchCV, GroupKFold, train_test_split, StratifiedKFold
from sklearn.feature_selection import SelectPercentile, SelectKBest, f_classif, RFECV
from sklearn.pipeline import Pipeline
import sklearn.metrics
from sklearn.metrics import make_scorer, roc_auc_score, average_precision_score
import sklearn.model_selection
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import label_binarize
from scipy import stats
from util.utils import get_calibration_metrics
from sklearn.utils import resample
import torch
from torch import nn
from torch import Tensor
from torch.autograd import grad
from torch.utils.data import DataLoader
from torch.utils.data import TensorDataset
from torch.utils.data import Dataset
from torch.utils.data.sampler import SubsetRandomSampler
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm, trange
# #for GRU-D
# import torch
# print("2.75")
# try:
# from GRUD import *
# except:
# from utils.GRUD import *
# try:
# from EmbeddingAutoencoder import ae_tf, ae_keras, rnn_tf, rnn_tf2
# except:
# from utils.EmbeddingAutoencoder import ae_tf, ae_keras, rnn_tf, rnn_tf2
# import umap
import datetime
import random
from tqdm import tqdm
import pickle
import matplotlib.pyplot as plt
import time
# # list global variables
# In[2]:
filtered_df=None
label_df=None
years_df=None
sites_df=None
common_indices=None
y_df=None
embedded_model=None
scaler=None
best_params=None
train_cv_results=None
keep_cols=None
train_means=None
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def get_measures(y, y_pred_prob, pred, modeltype):
try:
AUC=sklearn.metrics.roc_auc_score(y, y_pred_prob)
except Exception as err:
print("couldn't compute AUC: {}".format(err))
AUC=np.nan
try:
APR=sklearn.metrics.average_precision_score(y, y_pred_prob)
except Exception as err:
print("couldn't compute APR: {}".format(err))
APR=np.nan
try:
F1=sklearn.metrics.f1_score(y, pred)
ACC=sklearn.metrics.accuracy_score(y, pred)
except Exception as err:
print("couldn't compute F1, ACC: {}".format(err))
F1=ACC=np.nan
try:
if (modeltype in ['1class_svm', '1class_svm_novel', 'iforest', 'svm']):
## min-max scaling of y_pred
p = (y_pred_prob - np.min(y_pred_prob))/ (np.max(y_pred_prob) - np.min(y_pred_prob))
else:
p=y_pred_prob
_,_,ECE,MCE = get_calibration_metrics(y, p, 10, 'quantile')
except Exception as err:
print("couldn't compute ECE,MCE: {}".format(err))
ECE = MCE = np.nan
try:
if (modeltype in ['1class_svm', '1class_svm_novel', 'iforest', 'svm']):
## min-max scaling of y_pred
p = (y_pred_prob - np.min(y_pred_prob))/ (np.max(y_pred_prob) - np.min(y_pred_prob))
else:
p=y_pred_prob
O_E = np.mean(p)/np.mean(y) ## observed-mean over expected-mean
except Exception as err:
print("couldn't compute O_E: {}".format(err))
O_E = np.nan
return AUC, F1, ACC, APR, ECE, MCE, O_E
def get_prediction(modeltype, model, X_df, y, subject_id):
# Different models have different score funcions
if modeltype in ['lstm','gru']:
y_pred_prob=model.predict(np.swapaxes(X_df, 1,2))
pred = list(map(int, y_pred_prob > 0.5))
elif modeltype=='grud':
#create test_dataloader X_df, y_df
test_dataloader=PrepareDataset(X_df, y, subject_id, train_means, BATCH_SIZE = 1, seq_len = 25, ethnicity_gender=True, shuffle=False)
predictions, labels, _, _ = predict_GRUD(model, test_dataloader)
y_pred_prob=np.squeeze(np.asarray(predictions))[:,1]
y=np.squeeze(np.asarray(labels))
pred=np.argmax(np.squeeze(predictions), axis=1)
# ethnicity, gender=np.squeeze(ethnicity), np.squeeze(gender)
elif modeltype in ['lr', 'rf', 'mlp', 'knn', 'nb']:
y_pred_prob=model.predict_proba(X_df)[:,1]
pred=model.predict(X_df)
elif modeltype in ['svm']:
y_pred_prob=model.decision_function(X_df)
pred=model.predict(X_df)
elif modeltype in ['rbf-svm']:
y_pred_prob=model.predict_proba(X_df)[:,1]
pred=[1 if x > 0.5 else 0 for x in y_pred_prob]
elif modeltype in ['1class_svm', 'iforest', '1class_svm_novel']:
## one-class classifier
y_pred_prob= -1.0 * model.decision_function(X_df)
pred= model.predict(X_df)
pred[pred==1] = 0
pred[pred==-1] = 1
elif modeltype == 'mlp_torch':
y_pred_prob = predict_mlp_torch(model, X_df.values, y, batch_size=64)
pred=[1 if x > 0.5 else 0 for x in y_pred_prob]
else:
raise Exception('dont know proba function for classifier = "%s"' % modeltype)
return y, y_pred_prob, pred
labels = np.unique(y_true)
if len(labels) > 2:
raise ValueError("Only binary classification is supported. "
"Provided labels %s." % labels)
y_true = label_binarize(y_true, classes=labels)[:, 0]
if bin_strategy == 'quantile': ## equal-frequency bins
# Determine bin edges by distribution of data
quantiles = np.linspace(0, 1, n_bins + 1)
bins = np.percentile(y_prob, quantiles * 100)
bins[-1] = bins[-1] + 1e-8
elif bin_strategy == 'uniform': ## equal-width bins
bins = np.linspace(0., 1. + 1e-8, n_bins + 1)
else:
raise ValueError("Invalid entry to 'bin_strategy' input. bin_Strategy "
"must be either 'quantile' or 'uniform'.")
binids = np.digitize(y_prob, bins) - 1
bin_sums = np.bincount(binids, weights=y_prob, minlength=len(bins))
bin_true = np.bincount(binids, weights=y_true, minlength=len(bins))
bin_total = np.bincount(binids, minlength=len(bins))
nonzero = bin_total != 0
prob_true = (bin_true[nonzero] / bin_total[nonzero])
prob_pred = (bin_sums[nonzero] / bin_total[nonzero])
abs_error = np.abs(prob_pred - prob_true)
expected_error = np.average(abs_error, weights=(bin_total / y_true.size)[nonzero])
max_error = np.max(abs_error)
return prob_true, prob_pred, expected_error, max_error
def get_ECE(y, y_pred, **kwargs):
_, _, ECE, _ = get_calibration_metrics(y_true=y, y_prob=y_pred, n_bins=10, bin_strategy='quantile')
return ECE
def get_MCE(y, y_pred, **kwargs):
_, _, _, MCE = get_calibration_metrics(y_true=y, y_prob=y_pred, n_bins=10, bin_strategy='quantile')
return MCE
def get_globals():
"""
Get all the global variables. Useful for when the script is being imported
Returns:
filtered_df, label_df, years_df, common_indices, y_df, embedded_model, scaler, best_params
"""
global filtered_df
global label_df
global years_df
return filtered_df, label_df, years_df, common_indices, y_df, embedded_model, scaler, best_params
def save_filtered_data(data_dir):
t0 = time.time()
if len(data_dir)>0:
DATA_DIR=os.path.join(data_dir, 'filtered_data.h5')
else:
DATA_DIR='E:/Data/HIDENIC_EXTRACT_OUTPUT_DIR/POP_SIZE_100/ITEMID_REP/filtered_data_100.h5'
filtered_df.to_hdf(DATA_DIR, key='filtered_df', mode='a')
y_df.to_hdf(DATA_DIR, key='y_df', mode='a')
label_df.to_hdf(DATA_DIR, key='label_df', mode='a')
pd.Series(common_indices).to_hdf(DATA_DIR, key='common_indices', mode='a')
t1 = time.time()
print("finished saving filtered data in {:10.1f} seconds.".format(t1-t0))
return
def load_data(max_time=24, gap_time=12, data_dir="", load_filtered_data=False):
"""
Load the data from a static file at the specified data_dir extension
Inputs:
max_time (int): the maximum number of hours to use for the prediction task
gap_time (int): the minimum number of hours between the maximum time and the prediction task. We don't want the prediction task happening within, or immediately after the observation period.
data_dir (str): the path to where the data are contained
Returns:
None : the results are updated as globals.
"""
global filtered_df
global label_df
global common_indices
global y_df
if load_filtered_data:
t0 = time.time()
if len(data_dir)>0:
DATA_DIR=os.path.join(data_dir, 'filtered_data.h5')
else:
DATA_DIR='E:/Data/HIDENIC_EXTRACT_OUTPUT_DIR/POP_SIZE_100/ITEMID_REP/filtered_data_100.h5'
filtered_df=pd.read_hdf(DATA_DIR, key='filtered_df')
y_df=pd.read_hdf(DATA_DIR, key='y_df')
label_df=pd.read_hdf(DATA_DIR, key='label_df')
common_indices=pd.read_hdf(DATA_DIR, key='common_indices').tolist()
t1 = time.time()
print("finished loading filtered data in {:10.1f} seconds.".format(t1-t0))
return
t0 = time.time()
if len(data_dir)>0:
DATA_DIR=os.path.join(data_dir, 'all_hourly_data.h5')
else:
DATA_DIR='E:/Data/HIDENIC_EXTRACT_OUTPUT_DIR/POP_SIZE_100/ITEMID_REP/all_hourly_data_100.h5'
if not(os.path.isfile(DATA_DIR)):
DATA_DIR=input('Could not find data.hdf. Please enter the full path to the file:\n')
if not(os.path.isfile(DATA_DIR)):
raise('Not a valid directory:\n {}'.format(DATA_DIR))
df=pd.read_hdf(DATA_DIR, key='vitals_labs')
t1 = time.time()
print("finished reading vitals_labs features in {:10.1f} seconds.".format(t1-t0))
# add the hours_in index as a column
# if not(isinstance(df.index.names[3], str)):
# col_name=df.index.names[3].decode()
# col_values=df.index.values
# col_values=[values[3] for values in col_values]
# print(df.index.values.shape)
idx = pd.IndexSlice
if len(data_dir)>0:
OUTCOMES_DIR=os.path.join(data_dir, 'static_data.csv')
else:
OUTCOMES_DIR='E:/Data/HIDENIC_EXTRACT_OUTPUT_DIR/POP_SIZE_100/ITEMID_REP/static_data_100.csv'
if not(os.path.isfile(OUTCOMES_DIR)):
OUTCOMES_DIR=input('Could not find static.csv. Please enter the full path to the file:\n')
if not(os.path.isfile(OUTCOMES_DIR)):
raise('Not a valid directory')
y_df=pd.read_csv(OUTCOMES_DIR, index_col=0)
y_df.drop(columns='icustay_id', inplace=True)
y_df=y_df.set_index(['hadm_id'], append=True)
#rename the index to match other columns
# (Amin) why encode() names?! remove for now
# y_df.index.rename([name.encode() for name in y_df.index.names], inplace=True)
y_df.index.rename([name for name in y_df.index.names], inplace=True)
#rename the columns to match other column levels
column_names=y_df.columns.tolist()
# (added by Amin)
y_df.columns.name = 'item_id'
# for i in range(3):
# y_df=pd.concat([y_df], axis=1, keys=['OUTCOMES']).swaplevel(0, 1, 1).swaplevel(0, 1, 1)
# for level, item in enumerate(['itemid'.encode()]):
# y_df.columns=y_df.columns.rename(item, level=level)
# y_df.columns.set_levels(column_names,level=level,inplace=True)
# y_df.columns.set_labels([[i for i in range(len(y_df.columns.levels[0]))] for i in range(4)],level=[0,1,2,3],inplace=True)
# y_df.loc[:, (slice(None), slice(None), slice(None), 'los_icu')]*=24 #icu data from days to hours
y_df.loc[:, 'los_icu']*=24 #icu data from days to hours
# mask = y_df.loc[:,(slice(None), slice(None), slice(None), 'los_icu')].values>max_time+gap_time
mask = y_df.loc[:, 'los_icu'].values > max_time+gap_time
# y_df=y_df.loc[idx[mask, :, :], :]
y_df=y_df.loc[idx[mask, :], :]
outcomes_df=y_df.copy()
# categories=['asian', 'black', 'hispanic','white']
# name=y_df.loc[:, idx[:,:,:,'ethnicity']].values.ravel()
# for category in categories:
# name[[i for i, item in enumerate(name) if category in item.lower()]]=category
# name[[i for i, item in enumerate(name) if item not in categories]]='other'
# for category in categories+['other']:
# y_df.loc[:, idx[category, category, category,category]]=[1 if item in category else 0 for item in name]
# #same for gender
# name=y_df.loc[:, idx[:,:,:,'gender']].values.ravel()
# y_df.loc[:, idx['F','F','F','F']]=[1 if 'f' in item.lower() else 0 for item in name]
# y_df.loc[:, idx['M','M','M','M']]=[1 if 'm' in item.lower() else 0 for item in name]
y_df = pd.get_dummies(y_df, columns=['gender', 'race'])
common_indices=outcomes_df.index.tolist()
# common_indices=list(set(outcomes_df.index.get_level_values(outcomes_df.index.names.index('hadm_id'.encode()))).intersection(set(df.index.get_level_values(df.index.names.index('hadm_id')))))
common_indices=list(set(outcomes_df.index.get_level_values('hadm_id')).intersection(set(df.index.get_level_values('hadm_id'))))
t0 = time.time()
#apply common indices
df=df.loc[idx[:, common_indices, :,:],:]
y_df=y_df.loc[idx[:, common_indices, :], :]
t1 = time.time()
print("applied common indices in {:10.1f} seconds.".format(t1-t0))
filtered_df=df.copy()
filtered_df.index.names=df.index.names
label_df=outcomes_df.copy()
# label_df.columns=label_df.columns.droplevel([0,1,2]) # only do this once
label_df['los_3']=np.zeros((len(label_df),1)).ravel()
label_df.loc[label_df['los_icu']>=3*24, 'los_3']=1
return
# In[5]:
def generate_labels(label_df, subject_index, label):
"""
Get the labels for a particular target matching the subject index
Input:
label_df (pd.DataFrame): the dataframe containing the desired labels
subject_index (list): the indices of the data to find the training labels
label (str): the name of the desired label
Returns:
(list): all of the labels for the given dubject index and label
"""
return label_df.loc[subject_index, label].values.tolist()
# In[6]:
def impute_simple(df, time_index=None):
"""
concatenate the forward filled value, the mask of the measurement, and the time of the last measurement
refer to paper
Z. Che, S. Purushotham, K. Cho, D. Sontag, and Y. Liu, "Recurrent Neural Networks for Multivariate Time Series with Missing Values," Scientific Reports, vol. 8, no. 1, p. 6085, Apr 2018.
Input:
df (pandas.DataFrame): the dataframe with timeseries data in the index.
time_index (string, optional): the heading name for the time-series index.
Returns:
df (pandas.DataFrame): a dataframe according to the simple impute algorithm described in the paper.
"""
#masked data
masked_df=pd.isna(df.drop(columns=['count', 'std'], level=1))
masked_df=masked_df.astype(int)
masked_df.rename({'mean': 'is_nan'}, axis=1, level=1, inplace=True)
#time since last measurement
if not(time_index):
time_index='hours_in' #.encode()
index_of_hours=list(df.index.names).index(time_index)
time_in=[item[index_of_hours] for item in df.index.tolist()]
time_df=df.drop(columns=['mean', 'std'], level=1)
for col in time_df.columns.tolist():
time_df[col]=time_in
# time_df[masked_df]=np.nan
time_df.rename({'count': 'time'}, axis=1, level=1, inplace=True)
#concatenate the dataframes
df_prime=pd.concat([df, masked_df, time_df], axis=1)
df_prime.columns=df_prime.columns.rename("simple_impute", level=0)#rename the column level
#fill each dataframe using either ffill or mean
df_prime=df_prime.unstack().fillna(0)
#swap the levels so that the simple imputation feature is the lowesst value
col_level_names=list(df_prime.columns.names)
col_level_names.append(col_level_names.pop(0))
df_prime=df_prime.reorder_levels(col_level_names, axis=1)
df_prime.sort_index(axis=1, inplace=True)
return df_prime
# # def read_years_data
# In[7]:
def read_years_data(data_dir=""):
"""
Read the csv linking the years to the dataset (not reproducible without limited use agreement).
Input:
data_dir (str): the path to the mimic year map
"""
global years_df
global common_indices
global y_df
# if len(data_dir)>0:
# pathname=os.path.join(data_dir,'yearmap_2018_07_20_tjn.csv' )
# else:
# pathname="/scratch/tjn/mimic-years/yearmap_2018_07_20_tjn.csv"
# if not(os.path.isfile(pathname)):
# pathname=input('Could not find yearmap_2018_07_20_tjn.csv. Please enter the full path to the file:\n')
# if not(os.path.isfile(pathname)):
# raise('Not a valid directory for years_df')
# years_df=pd.read_csv(pathname, index_col=0, header=None)
years_df = y_df.reset_index()[['hadm_id', 'intime']].set_index('hadm_id')
years_df['year'] = pd.to_datetime(years_df['intime']).dt.year
years_df['month'] = pd.to_datetime(years_df['intime']).dt.month
years_df.drop(columns=['intime'], inplace=True)
# years_df.columns=["hadm_id".encode(), "year"]
# years_df.set_index('hadm_id'.encode(), inplace=True)
years_df=years_df.loc[common_indices]
print(" loaded years")
return
def read_sites_data(data_dir=""):
"""
"""
global sites_df
global common_indices
if len(data_dir)>0:
DATA_PATH=os.path.join(data_dir, 'site_info.pkl')
else:
DATA_PATH='E:/Data/HIDENIC_EXTRACT_OUTPUT_DIR/POP_SIZE_100/ITEMID_REP/site_info.pkl'
sites_df = pd.read_pickle(DATA_PATH)
sites_df = sites_df.set_index('hadm_id')
sites_df=sites_df.loc[common_indices]
print("loaded sites info")
return
# In[8]:
def flattened_to_sequence(X, vect=None):
"""
Turn pandas dataframe into sequence
Inputs:
X (pd.DataFrame): a multiindex dataframe of MIMICIII data
vect (tuple) (optional): (timesteps, non-time-varying columns, time-varying columns, vectorizer(dict)(a mapping between an item and its index))
Returns:
X_seq (np.ndarray): Input 3-dimensional input data with the [n_samples, n_features, n_hours]
"""
hours_in_values=X.index.get_level_values(X.index.names.index('hours_in'))
output=np.dstack((X.loc[(slice(None), slice(None), i), :].values for i in sorted(set(hours_in_values))))
#ex. these are the same
# print(output[0,:10, 5])
# print(X.loc[(X.index.get_level_values(0)[0], X.index.get_level_values(1)[0], 5), X.columns.tolist()[:10]].values)
return output, None
def get_ctakes_level(df_in, abs_val=True):
"""
Replaces itemids with ctakes outputs by averaging across outcomes throughout time.
Inputs:
df_in (df): the original itemid df.
Returns:
cui_df (df): a dataframe with the ctakes column headings
"""
filename=os.path.join(os.getcwd(), 'ctakes_extended_spanning.p')
# print(filename)
if os.path.exists(filename):
with open(filename , 'rb') as f:
mappings=pickle.load(f)
else:
raise Exception('no file named {}'.format(filename))
mappings=dict(mappings) #dict of itemid: [cuis]
columns=df_in.columns.tolist()
try:
col_number=list(df_in.columns.names).index('itemid'.encode()) #drop unecessary index
except:
col_number=list(df_in.columns.names).index('itemid') #drop unecessary index
itemids=list(df_in.columns.get_level_values(col_number))
#remove all itmeids that aren't in our itemids
# print("deleting unecessary keys")
for key in list(mappings.keys()):
try:
k2=int(key.split("_")[0])
if k2 not in itemids:
raise
except:
del mappings[key]
reverse_mappings=invert_dict(mappings) # dict of cui: [itemids]
all_features=sorted(list(reverse_mappings.keys()))
cui_df=pd.DataFrame(index=df_in.index)
for cui in sorted(list(reverse_mappings.keys())):
for item in reverse_mappings[cui]:
cols=[]
try:
item=int(item.split('_')[0])
except:
continue
if item in itemids:
cols.append(columns[itemids.index(item)])
if len(cols)!=1:
cols=list(zip(*cols))
try:
data_selection=df_in.loc[:, cols].values
except:
# print(cols)
# print(list(zip(*cols)))
raise Exception("cannot index dataframe with the columns: {}".format(cols))
averaged_selection=np.mean(data_selection, axis=1)
if abs_val:
averaged_selection=np.abs(averaged_selection)
#append averaged selection to list
cui_df.loc[:, cui]=averaged_selection
cui_df.columns.names=['cui']
return cui_df
# # def data_preprocessing
# In[45]:
def data_preprocessing(df_in, level, imputation_method, target, embedding, is_time_series,
timeseries_vect=None, representation_vect=None, impute=True):
"""
Clean the data into machine-learnable matrices.
Inputs:
df_in (pd.DataFrame): a multiindex dataframe of MIMICIII data
level (string or bytes): the level of the column index to use as the features level
imputation_method (string): the method for imputing the data, either Forward, or Simple
Target (string): the heading to select from the labels in the outcomes_df, i.e. LOS or died
Returns:
X (pd.DataFrame): the X data to input to the model
y (array): the labels for the corresponding X-data
"""
global y_df
global embedded_model
global scaler
global keep_cols
idx = pd.IndexSlice
# (Amin) no level 2 in HIDENIC
# if level.lower() == 'level2'.encode():
# level = 'LEVEL2'.encode()
if level=='nlp'.encode():
col_level=list(df_in.columns.names).index('itemid'.encode()) # get the index of the column level desired
else:
col_level=list(df_in.columns.names).index(level) # get the index of the column level desired
# test_df=df_in.mean(axis=1, level=col_level).copy() # average across that column level
test_df=df_in.copy()
del df_in
# index_level=list(test_df.index.names).index('icustay_id') #drop unecessary index
# test_df.index=test_df.index.droplevel(index_level)
test_df.index=test_df.index.droplevel('icustay_id') #drop unecessary index
# if it is nlp to scaler-> groupings -> imputation
if level == 'nlp'.encode():
# Not sure if this is desired or not
# #standard scaler first
# if representation_vect is None:
# print('\n', '*'*63)
# print("fitting new scaler")
# # first stack the columns
# test_df.index.names=[name.decode() if not(isinstance(name, str)) else name for name in test_df.index.names]
# test_df.columns.names=[name.decode() if not(isinstance(name, str)) else name for name in test_df.columns.names]
# #find any columns where the values are all the same (treat as unmeasured)
# # # now remove the columns with redundant values
# # keep_cols=test_df.columns.tolist()
# # keep_cols=[col for col in keep_cols if len(test_df[col].unique())!=1]
# # print(test_df.values.shape)
# # test_df=test_df[keep_cols]
# # print(test_df.values.shape)
# # pandas scaler version
# df_means=test_df.mean(skipna=True, axis=0)
# df_stds=test_df.std(skipna=True, axis=0)
# print(df_means.shape, df_stds.shape)
# print(len(df_stds.values))
# print(len(df_stds.values==0))
# print(sum(df_stds.values==0))
# print(len(df_stds))
# print(len(df_stds.loc[df_stds.values==0]))
# print(df_means.loc[df_stds.values==0])
# #where std dev ==0 replace with mean
# df_stds.loc[df_stds.values==0]=df_means.loc[df_stds.values==0]
# scaler=(df_means, df_stds)
# print("got scaler")
# index=test_df.index.tolist()
# columns=test_df.columns.tolist()
# # X_df[X_df.columns]=(X_df[X_df.columns]-df_means)/df_stds
# data=(test_df[test_df.columns]-df_means)/df_stds
# print("data: ", np.sum(np.sum(np.isnan(data.astype(np.float32)))))
# test_df=pd.DataFrame(data, index=index, columns=columns)
# print("finished scaler")
# else:
# test_df=test_df[keep_cols]
# try:
# test_df.loc[:, test_df.columns]=scaler.transform(test_df.loc[:, test_df.columns].values.astype(np.float32))
# except:
# print("IN EXCEPT VISCIOISSSSSS____________________")
# # df_means, df_stds=scaler
# # test_df[test_df.columns]=(test_df[test_df.columns]-df_means)/df_stds
# df_means, df_stds =scaler
# print(np.sum(np.isnan(df_means)), np.sum(np.isnan(df_stds)))
# index=test_df.index.tolist()
# columns=test_df.columns.tolist()
# # X_df[X_df.columns]=(X_df[X_df.columns]-df_means)/df_stds
# data=(test_df[test_df.columns]-df_means)/df_stds
# test_df=pd.DataFrame(data, index=index, columns=columns)
# test_df.columns.names=['itemid'.encode()]
#then groupby ctakes
test_df=get_ctakes_level(test_df, abs_val=False)
#take care of imputation
if impute:
if imputation_method=='Forward':
imputed_df=test_df.fillna(method='ffill').unstack().fillna(0)
imputed_df.sort_index(axis=1, inplace=True)
elif imputation_method=='Simple':
print("imputing simple")
imputed_df=impute_simple(test_df)
print("imputed")
else:
imputed_df=test_df.unstack().sort_index(axis=1).copy()
#index contains subject_id and hadm_id. column contains level and hour
del test_df
#add categorical/demographic data AFTER EMBEDDING????
feature_names=imputed_df.columns.tolist()
imputed_df_old=imputed_df.copy()
col_level_names=imputed_df.columns.names
column_names=y_df.columns.tolist()
if y_df.columns.nlevels != imputed_df.columns.nlevels:
# print("making y_df levels equal to imputed_df ...")
for i in range((imputed_df.columns.nlevels - 1)):
y_df=pd.concat([y_df], axis=1, keys=['OUTCOMES']) #.swaplevel(0, 1, 1).swaplevel(0, 1, 1)
for level, item in enumerate(list(imputed_df.columns.names)):
y_df.columns=y_df.columns.rename(item, level=level)
y_df.columns.set_levels(column_names,level=level,inplace=True)
# y_df.columns.set_labels([[i for i in range(len(y_df.columns.levels[0]))] for i in range(3)],level=[0,1,2],inplace=True)
y_df.columns.set_codes([[i for i in range(len(y_df.columns.levels[0]))] for i in range(3)],level=[0,1,2],inplace=True)
# print("getting correct number of column levels")
# make both dataframes have the same number of column levels
while len(y_df.columns.names)!=len(imputed_df.columns.names):
if len(y_df.columns.names)>len(imputed_df.columns.names):
y_df.columns=y_df.columns.droplevel(0)
elif len(y_df.columns.names)<len(imputed_df.columns.names):
raise Exception("number of y_df columns is less than the number of imputed_df columns")
y_df=pd.concat([y_df], names=['Firstlevel'])
# print("got correct number of column levels")
# make both dataframes have the same column names
y_df.columns.names=imputed_df.columns.names
# print("imputed_df #null cols=%d" % imputed_df.isna().all(axis=0).sum())
# print("y_df #null cols=%d" % y_df.isna().all(axis=0).sum())
del imputed_df
X_df=imputed_df_old.copy()
del imputed_df_old #for memory sake
# if level in ['LEVEL2'.encode(), 'itemid'.encode()]:
if True:
#standard scaler
if representation_vect is None:
print('\n', '*'*63)
print("fitting new scaler")
#find any columns where the values are all the same (treat as unmeasured)
# first stack the columns
X_df.index.names=[name.decode() if not(isinstance(name, str)) else name for name in X_df.index.names]
X_df.columns.names=[name.decode() if not(isinstance(name, str)) else name for name in X_df.columns.names]
X_df=X_df.stack(level='hours_in', dropna=False)
print("X_df #null cols=%d" % X_df.isna().all(axis=0).sum())
# now remove the columns with redundant values
keep_cols=X_df.columns.tolist()
keep_cols=[col for col in keep_cols if len(X_df[col].unique())!=1]
X_df=X_df[keep_cols]
#now we can unstack the hours and sort them to the same as the original dataframe
X_df=X_df.unstack()
print("X_df #null cols=%d" % X_df.isna().all(axis=0).sum())
if impute:
X_df.columns=X_df.columns.swaplevel('hours_in', 'simple_impute')
#take the columns again so that we don't have to unstack every time
keep_cols=X_df.columns.tolist()
# pandas scaler version
print("starting scaler")
print("X_df: ",np.sum(np.sum(np.isnan(X_df.values.astype(np.float32)))))
df_means=X_df.mean(skipna=True, axis=0)
df_stds=X_df.std(skipna=True, axis=0)
#where std dev ==0 replace with mean
df_stds.loc[df_stds.values==0, :]=df_means.loc[df_stds.values==0, :]
scaler=(df_means, df_stds)
print("got scaler")
index=X_df.index.tolist()
columns=X_df.columns.tolist()
# print(df_stds.loc[df_stds.values==0, :])
# print(np.sum(df_stds.values==0))
# X_df[X_df.columns]=(X_df[X_df.columns]-df_means)/df_stds
# (Amin) line below introduces NAs/Infs if any(df_stds==0), impute with 0 after scaling
data=(X_df[X_df.columns]-df_means)/df_stds
count_na = np.sum(np.sum(np.isnan(data.astype(np.float32))))
# print("data count_na: ", count_na)
X_df=pd.DataFrame(data, index=index, columns=columns)
# print("finished scaler")
else:
X_df=X_df[keep_cols]
try:
X_df.loc[:, X_df.columns]=scaler.transform(X_df.loc[:, X_df.columns].values.astype(np.float32))
except:
df_means, df_stds =scaler
index=X_df.index.tolist()
columns=X_df.columns.tolist()
# X_df[X_df.columns]=(X_df[X_df.columns]-df_means)/df_stds
data=(X_df[X_df.columns]-df_means)/df_stds
X_df=pd.DataFrame(data, index=index, columns=columns)
## impute if NAs/Infs
X_df.replace([np.inf, -np.inf], np.nan, inplace=True)
count_na = X_df.isna().all(axis=0).sum()
if count_na>0:
# print("X_df #null cols=%d" % count_na)
# print("imputing NAs with 0")
X_df.fillna(0, inplace=True)
# print("X_df #null cols=%d" % count_na)
# print("X_df #null cols=%d" % X_df.isna().all(axis=0).sum())
#keep this df for adding categorical data after
demo_df=y_df.copy()
# (AMIN) temporarily commenting next 2 lines
# demo_df.index.names=[name.decode() if not(isinstance(name, str)) else name for name in demo_df.index.names]
# demo_df.columns.names=[name.decode() if not(isinstance(name, str)) else name for name in demo_df.columns.names]
demo_df.columns=demo_df.columns.droplevel(demo_df.columns.names.index('hours_in'))
# structure for the resot of the function is:
# if is_timeseries:
# learn representation in {raw, umap, autoencoder, pca}
# append demographic data
# else:
# append demographic data
# learn representation in {raw, umap, autoencoder, pca}
# get labels
# Should the data be a time series or flattened?
if is_time_series:
print("timeseries")
subject_index=[(item[0], item[1]) for item in X_df.index.tolist()] #select the subject_id and hadm_id
X_df.index.names=[name.decode() if not(isinstance(name, str)) else name for name in X_df.index.names]
X_df.columns.names=[name.decode() if not(isinstance(name, str)) else name for name in X_df.columns.names]
X_df=X_df.stack(level='hours_in', dropna=False) #.set_index('hours_in', append=True).values#stack the time level and add it to the index
X_df=X_df.join(demo_df.loc[:, ['M', 'F', 'asian', 'black','hispanic','white', 'other']], how='inner', on=['subject_id', 'hadm_id'])
X_df.index.names=['subject_id', 'hadm_id', 'hours_in']
X_df[X_df.columns]= X_df[X_df.columns].values.astype(np.float32)
print(np.sum(np.sum(np.isnan(X_df.values))))
#get list of gender and ethnicity here.
gender=X_df.loc[(slice(None), slice(None), 0), 'F'].values.ravel()
ethnicity=X_df.loc[(slice(None), slice(None), 0), ['asian', 'black','hispanic','white', 'other']].values
#one hot encode ethnicity
ethnicity=np.argmax(ethnicity, axis=1).ravel()
assert gender.shape==ethnicity.shape
if impute:
# gru-d shouldn't be flattened yet
X_df, timeseries_vect = flattened_to_sequence(X_df, timeseries_vect)
print(np.sum(np.sum(np.sum(np.isnan(X_df)))))
assert len(ethnicity)==len(X_df)
#embedd
if embedding == 'raw':
if representation_vect is None:
representation_vect = ('raw', 'raw')
elif embedding=="autoencoder":
# combine the timeseries data which is in shape [n_samples, n_features, n_hours]
if not(impute):
raise Exception("Embedding autoencoder is not implemented for models that do not require imputation")
print(X_df.shape)
x_train=X_df.reshape((-1, X_df.shape[1]))
if representation_vect is None:
learning_rate=np.logspace(-5, -1, num=5)
dim_l1=np.asarray([128, 256, 512, 1028, 2048])
dim_l2=np.asarray([64, 128, 256, 512, 1028])
losses=[]
for i in range(10):
lr=random.choice(learning_rate)
num_hidden_1=random.choice(dim_l1)
num_hidden_2=random.choice(dim_l2[np.where(dim_l2<=num_hidden_1)])
num_input = x_train.shape[1] # MNIST data input (img shape: 28*28)
embedded_model=ae_keras(num_input, num_hidden_1, num_hidden_2, lr=lr)
loss=embedded_model.fit(x_train, epochs=1)
losses.append((loss, lr, num_hidden_1, num_hidden_2))
for loss in sorted(losses, key=lambda x:x[0]):
print("loss: {}, lr: {}, num hidden 1: {}, num hidden 2: {}".format(loss[0], loss[1], loss[2], loss[3]))
lowest_loss=sorted(losses, key=lambda x:x[0])[0]
num_hidden_1 = lowest_loss[2] # 1st layer num features
num_hidden_2 = lowest_loss[3] # 2nd layer num features (the latent dim)
lr=lowest_loss[1]
num_input = x_train.shape[1] # MNIST data input (img shape: 28*28)
embedded_model=ae_keras(num_input, num_hidden_1, num_hidden_2, lr=lr)
# WARNING: SHOULDNT BE FITTING ON THE TEST DATA
embedded_model.fit(x_train, epochs=1, save=True)
output_dim=num_hidden_2
representation_vect = (embedded_model, output_dim)
else:
(_, output_dim) = representation_vect
try:
all_hours=[]
for i in range(X_df.shape[2]):
all_hours.append(embedded_model.transform(X_df[:,:,i]))
X_df=np.dstack(all_hours)