-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexperiments_new.py
3735 lines (2932 loc) · 167 KB
/
experiments_new.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
"""
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")
# from operator import mod
import pandas as pd
import numpy as np
import os
import pathlib
from scipy.sparse.construct import rand
import scipy.stats as stats
# from scipy.stats.stats import mode
### sklearn tools
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 sklearn.model_selection import ParameterGrid
from scipy import stats
from sklearn.utils import resample
# XGboost
import xgboost as xgb
# calibration tools
from HIDENIC_overtime_analysis.util.utils import get_calibration_metrics
# https://pypi.org/project/uncertainty-calibration/
import calibration as cal
from category_encoders import TargetEncoder
## independence test and measures
from hyppo.ksample import KSample, MMD
from hyppo.tools import chi2_approx
import ot
## SHAP explanation library
import shap
# 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 random
from tqdm import tqdm
import pickle
# import matplotlib.pyplot as plt
import time
# # list global variables
filtered_df=None
label_df=None
years_df=None
sites_df=None
common_indices=None
demo_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, modeltype, threshold=0.5):
pred = np.array(y_pred_prob >= threshold).astype(int)
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(y)/np.mean(p) ## observed-mean over expected-mean
except Exception as err:
print("couldn't compute O_E: {}".format(err))
O_E = np.nan
try:
BRIER = sklearn.metrics.brier_score_loss(y, y_pred_prob)
except Exception as err:
BRIER = None
try:
CE = cal.get_calibration_error(y_pred_prob, y)
except Exception as err:
CE=None
try:
ECE2 = cal.get_ece(y_pred_prob, y)
except Exception as err:
ECE2=None
return {'AUC':AUC, 'F1':F1, 'ACC':ACC, 'APR':APR, 'ECE':ECE, 'MCE':MCE, 'O_E':O_E, 'BRIER':BRIER, 'CE':CE, 'ECE2':ECE2}
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, demo_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, demo_df, embedded_model, scaler, best_params
"""
global filtered_df
global label_df
global years_df
return filtered_df, label_df, years_df, common_indices, demo_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')
demo_df.to_hdf(DATA_DIR, key='demo_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(data_dir="", num_samples=None):
"""
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 demo_df
idx = pd.IndexSlice
if len(data_dir)>0:
DATA_DIR=os.path.join(data_dir, 'all_hourly_data.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))
print("reading vitals_labs")
t0 = time.time()
df=pd.read_hdf(DATA_DIR, key='vitals_labs')
df = df.droplevel("icustay_id")
t1 = time.time()
print("finished reading vitals_labs features in {:10.1f} seconds.".format(t1-t0))
if num_samples is not None:
print(f'selecting only {num_samples} rows from vitals_labs dataframe ...')
df=df.iloc[:num_samples,:]
print(df.shape)
# read demographics and otcomes
print("loading demographics ...")
demo_df = read_demographics(data_dir)
sites_df = read_sites_data(data_dir)
demo_df = demo_df.join(sites_df[['icu_unit', 'hospital', 'icu_category']], how='left')
demo_df = demo_df.droplevel("icustay_id")
del sites_df
print("demographics loaded")
## convert to datetime
demo_df.intime = pd.to_datetime(demo_df.intime)
# get common hospital stays
common_indices=list(set(demo_df.index.get_level_values('hadm_id')).intersection(set(df.index.get_level_values('hadm_id'))))
print("applying common indices ...")
t0 = time.time()
#apply common indices
demo_df=demo_df.loc[demo_df.index.get_level_values("hadm_id").isin(common_indices), :]
filtered_df=df.loc[df.index.get_level_values("hadm_id").isin(common_indices), :]
del df
t1 = time.time()
print("applied common indices in {:10.1f} seconds.".format(t1-t0))
## create label_df, consists of target variables only
label_df = demo_df[['mort_icu', 'los_icu']].copy()
label_df['los_3']=np.zeros((len(label_df),1)).ravel()
label_df.loc[label_df['los_icu']>=3*24, 'los_3'] = 1
demo_df['los_3'] = label_df['los_3'].values
return filtered_df, label_df, demo_df
def read_demographics(data_dir):
idx = pd.IndexSlice
if len(data_dir)>0:
DEMO_DIR=os.path.join(data_dir, 'static_data.csv')
else:
DEMO_DIR='E:/Data/HIDENIC_EXTRACT_OUTPUT_DIR/POP_SIZE_100/ITEMID_REP/static_data_100.csv'
if not(os.path.isfile(DEMO_DIR)):
DEMO_DIR=input('Could not find static.csv. Please enter the full path to the file:\n')
if not(os.path.isfile(DEMO_DIR)):
raise('Not a valid directory')
demo_df=pd.read_csv(DEMO_DIR, index_col=[0,1,2])
# demo_df = demo_df.droplevel('icustay_id')
demo_df.loc[:, 'los_icu']*=24 #icu data from days to hours
# mask = demo_df.loc[:, 'los_icu'].values > max_time+gap_time
# demo_df=demo_df.loc[idx[mask, :], :]
demo_df = pd.get_dummies(demo_df, columns=['gender', 'race'])
return demo_df
# 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, means=None, method='mean', missing_indicator=True):
"""
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.
"""
if missing_indicator:
masked_df=pd.isna(df)
masked_df=masked_df.astype(int)
masked_df.rename({'mean': 'is_nan'}, axis=1, level=1, inplace=True)
df_prime=pd.concat([df, masked_df], axis=1)
else:
df_prime=df.copy()
del df
df_prime.columns=df_prime.columns.rename("simple_impute", level=0)#rename the column level
#fill using ffill, bfill, and means
df_prime=df_prime.unstack().groupby(level=0, axis=1).apply(
lambda g: g.fillna(method='ffill', axis=1).fillna(method='bfill', axis=1))
if method=='mean':
if means is not None:
df_prime.fillna(means)
else:
df_prime.apply(lambda x: x.fillna(x.mean()))
#swap the levels so that the simple imputation feature is the lowest 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 demo_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 = demo_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.set_index(['subject_id', 'hadm_id', 'icustay_id'], inplace=True)
# sites_df=sites_df.loc[common_indices]
print("loaded sites info")
return sites_df
# 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(train_df, test_df, target, mode="basic", missing_rate_cutoff=0.8, imputation_method="simple_impute", transform_params=None):
"""
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 demo_df
global embedded_model
global scaler
global keep_cols
global select_cols
global hospital_target_encoder
global age_scaler
global demo_mode
idx = pd.IndexSlice
missing_indicator=True
if mode=="basic_no_indicator":
missing_indicator=False
if transform_params is not None:
scaler=transform_params["scaler"]
keep_cols=transform_params["keep_cols"]
select_cols=transform_params["select_cols"]
hospital_target_encoder=transform_params["hospital_target_encoder"]
age_scaler=transform_params["age_scaler"]
demo_mode=transform_params["demo_mode"]
if train_df is not None:
train_df = train_df.loc[:, idx[:, "mean"]] # drop count and std columns
# train_df = train_df.droplevel("icustay_id") #drop unecessary index level
if test_df is not None:
test_df = test_df.loc[:, idx[:, "mean"]] # drop count and std columns
# test_df = test_df.droplevel("icustay_id") #drop unecessary index level
# if mode == "basic": # just use labs & vitals with missing_rate <= missing_rate_cutoff
if train_df is not None:
# select features with missing_rate <= missing_rate_cutoff
missing_rates = train_df.isna().mean()
select_cols = missing_rates[missing_rates <= missing_rate_cutoff].index
train_df = train_df.loc[:, select_cols]
if test_df is not None:
test_df = test_df.loc[:, select_cols]
if imputation_method=="simple_impute":
print("imputing simple")
if train_df is not None:
train_df = impute_simple(train_df, means=None, missing_indicator=missing_indicator)
df_means=train_df.mean(skipna=True, axis=0)
df_stds=train_df.std(skipna=True, axis=0)
scaler=(df_means, df_stds)
if test_df is not None:
df_means, df_stds = scaler
test_df = impute_simple(test_df, means=df_means, missing_indicator=missing_indicator)
print("imputed")
#standard scaler
print("fitting new scaler")
if train_df is not None:
# first stack the columns
train_df=train_df.stack(level='hours_in', dropna=False)
# now remove the columns with redundant values
keep_cols=train_df.columns.tolist()
keep_cols=[col for col in keep_cols if len(train_df[col].unique())!=1]
train_df=train_df[keep_cols]
#now we can unstack the hours and sort them to the same as the original dataframe
train_df=train_df.unstack()
# if impute:
train_df.columns=train_df.columns.swaplevel('hours_in', 'simple_impute')
#take the columns again so that we don't have to unstack every time
keep_cols=train_df.columns.tolist()
# pandas scaler version
df_means=train_df.mean(skipna=True, axis=0)
df_stds=train_df.std(skipna=True, axis=0)
scaler=(df_means, df_stds)
train_df = (train_df-df_means)/df_stds
## impute NAs/Infs with zero (caused by rescaling and std=0)
# pd.options.mode.use_inf_as_na = True # replace inf with nan
train_df.replace([np.inf, -np.inf], np.nan, inplace=True) ## replace inf with nan
train_df.fillna(0, inplace=True)
if test_df is not None:
## fit scaler to test dataset
test_df = test_df[keep_cols]
df_means, df_stds =scaler
test_df = (test_df-df_means)/df_stds
## impute NAs/Infs with zero (caused by rescaling and std=0)
# pd.options.mode.use_inf_as_na = True # replace inf with nan
test_df.replace([np.inf, -np.inf], np.nan, inplace=True) ## replace inf with nan
test_df.fillna(0, inplace=True)
print("finished scaler")
## join demographic features
demo_column_names=demo_df.columns.tolist()
if train_df is not None:
nlevels = train_df.columns.nlevels
columns_names = train_df.columns.names
else:
nlevels = test_df.columns.nlevels
columns_names = test_df.columns.names
if demo_df.columns.nlevels != nlevels:
print("making demo_df levels equal to train_df/test_df ...")
for i in range((nlevels - 1)):
demo_df=pd.concat([demo_df], axis=1, keys=['DEMO']) #.swaplevel(0, 1, 1).swaplevel(0, 1, 1)
for level, item in enumerate(list(columns_names)):
demo_df.columns=demo_df.columns.rename(item, level=level)
demo_df.columns=demo_df.columns.set_levels(demo_column_names,level=level)
demo_df.columns=demo_df.columns.set_codes([[i for i in range(len(demo_df.columns.levels[0]))] for i in range(3)],level=[0,1,2])
# make both dataframes have the same number of column levels
while len(demo_df.columns.names)!=len(columns_names):
if len(demo_df.columns.names)>len(columns_names):
demo_df.columns=demo_df.columns.droplevel(0)
elif len(demo_df.columns.names)<len(columns_names):
raise Exception("number of demo_df columns is less than the number of train_df/test_df columns")
demo_cols = ['age'] + [c for c in demo_df.columns.get_level_values(0) if c.startswith('gender_') or c.startswith('race_')]
## join demos to train dataset
if train_df is not None:
right = demo_df.loc[[(item[0], item[1]) for item in train_df.index.tolist()], (slice(None), slice(None), demo_cols)].values.astype(np.float32)
left=train_df.values.astype(np.float32)
result=np.concatenate((left, right), axis=1) #slow step timeit for combiing np.random.rand(15000, 10000) with np.random.rand(15000, 7)-> concat=50 iterations 192.49 s , hstack=50 iterations 212.61 , append=50 iterations 233.63 s
ind=pd.MultiIndex.from_tuples([(item[0], item[1]) for item in train_df.index.tolist()], names=['subject_id', 'hadm_id'])
cols=train_df.columns.union(demo_df.loc[:, (slice(None), slice(None), demo_cols)].columns, sort=None)
train_df=pd.DataFrame(data=result, index=ind, columns=cols)
## fill any missing demographics with mean/mode
demo_mode = train_df.loc[:, idx[:,:, demo_cols[1:]]].mode().iloc[0,:]
train_df.loc[:, idx[:,:, demo_cols[1:]]].fillna(demo_mode, inplace=True)
## standardize age
age_mean, age_std = train_df.loc[:, idx[:,:, "age"]].mean(), train_df.loc[:, idx[:,:, "age"]].std()
age_scaler = (age_mean, age_std)
train_df.loc[:, idx[:,:, "age"]].fillna(age_mean, inplace=True)
train_df.loc[:, idx[:,:, "age"]] = (train_df.loc[:, idx[:,:, "age"]] - age_mean)/age_std
## target-encode Hospital
hospital_target_encoder = TargetEncoder(smoothing=1.0, handle_unknown='value')
hospital_target_encoder.fit(demo_df.loc[train_df.index, 'hospital'], demo_df.loc[train_df.index, target])
train_df.loc[:, idx["hospital","hospital", "hospital"]] = hospital_target_encoder.transform(
demo_df.loc[train_df.index, "hospital"]).values.ravel()
if test_df is not None:
## join demos to test dataset
right = demo_df.loc[[(item[0], item[1]) for item in test_df.index.tolist()], (slice(None), slice(None), demo_cols)].values.astype(np.float32)
left=test_df.values.astype(np.float32)
result=np.concatenate((left, right), axis=1) #slow step timeit for combiing np.random.rand(15000, 10000) with np.random.rand(15000, 7)-> concat=50 iterations 192.49 s , hstack=50 iterations 212.61 , append=50 iterations 233.63 s
ind=pd.MultiIndex.from_tuples([(item[0], item[1]) for item in test_df.index.tolist()], names=['subject_id', 'hadm_id'])
cols=test_df.columns.union(demo_df.loc[:, (slice(None), slice(None), demo_cols)].columns, sort=None)
test_df=pd.DataFrame(data=result, index=ind, columns=cols)
## fill any missing demographics with mode (transform)
test_df.loc[:, idx[:,:, demo_cols[1:]]].fillna(demo_mode, inplace=True)
## standardize age (transform to test)
age_mean, age_std = age_scaler
test_df.loc[:, idx[:,:, "age"]].fillna(age_mean, inplace=True)
test_df.loc[:, idx[:,:, "age"]] = (test_df.loc[:, idx[:,:, "age"]] - age_mean)/age_std
## target-encode Hospital
test_df.loc[:, idx["hospital","hospital", "hospital"]] = hospital_target_encoder.transform(
demo_df.loc[test_df.index, "hospital"]).values.ravel()
# train_subject_index=[(item[0], item[1]) for item in train_df.index.tolist()] #select the subject_id and hadm_id
# test_subject_index=[(item[0], item[1]) for item in test_df.index.tolist()] #select the subject_id and hadm_id
# try:
# #get list of gender and ethnicity here.
# gender=X_df.loc[(slice(None), slice(None)), (slice(None), slice(None), 'gender_F')].values.ravel()
# ethnicity=X_df.loc[(slice(None), slice(None)), (slice(None), slice(None), [c for c in X_df.columns.get_level_values(0) if c.startswith('race_')])].values
# #one hot encode ethnicity
# ethnicity=np.argmax(ethnicity, axis=1).ravel()
# except:
# #dimensionality reduction techniques lose feature levels so they are different shapes.
# gender=X_df.loc[(slice(None), slice(None)), ('gender_F', 0)].values.ravel()
# ethnicity=X_df.loc[(slice(None), slice(None)), ([c for c in X_df.columns.get_level_values(0) if c.startswith('race_')], 0)].values
# #one hot encode ethnicity
# ethnicity=np.argmax(ethnicity, axis=1).ravel()
# assert gender.shape==ethnicity.shape
train_y = None if train_df is None else label_df.loc[train_df.index, target]
test_y = None if test_df is None else label_df.loc[test_df.index, target]
transform_params={}
transform_params["scaler"]=scaler
transform_params["keep_cols"]=keep_cols
transform_params["select_cols"]=select_cols
transform_params["hospital_target_encoder"]=hospital_target_encoder
transform_params["age_scaler"]=age_scaler
transform_params["demo_mode"]=demo_mode
return train_df, train_y, test_df, test_y, transform_params #, timeseries_vect, representation_vect, gender, ethnicity, [item[0] for item in subject_index]
# GRU-D stuff
def time_since_last(arr, mask):
"""
Calculate the time since the last event
"""
output=np.ones_like(arr)
# same as
ones_index=np.asarray(np.where(mask==1)).ravel()
tmp=ones_index+1
# output[tmp[tmp<len(output)]]=1
# output[np.where(arr==0)]=0
zeros_index=np.asarray(np.where(arr==0)).ravel()
#fill values until the next zero
both=np.sort(np.unique(np.concatenate((ones_index, zeros_index))))
mask_zeros_index=np.asarray(np.where(mask==0)).ravel()
if len(mask_zeros_index)==0:
return output
diff=np.insert(np.diff(mask_zeros_index), 0, 0)#remove donsecutive elements (where diff==1)
# print(mask_zeros_index)
# print(diff)
mask_zeros_index=mask_zeros_index[diff!=1]
# print(mask_zeros_index)
for ind, val in enumerate(mask_zeros_index):
#get the next one or stop zero index
try:
end_of_seq=np.min(both[np.where(both>val)])
output[val:end_of_seq+1]=np.arange(1, end_of_seq+2-val)
except:
end_of_seq=len(output)
output[val:]=np.arange(1, len(output[val:])+1)
#zero index up to and including next one is np.arange(0, len_until_1+1)
for ind in zeros_index:
try:
next_one=np.min(both[np.where(both>ind)])
output[ind:next_one+1]=np.arange(0, next_one+1-ind)
except:
next_one=len(output)
output[ind:]=np.arange(0, len(output[ind:])+1)
return output
def PrepareDataset(df_input, y, subject_index_in, train_means, BATCH_SIZE = 40, seq_len = 25, ethnicity_gender=False, shuffle=False,
drop_last=True):
""" Prepare training and testing datasets and dataloaders.
Convert speed/volume/occupancy matrix to training and testing dataset.
The vertical axis of speed_matrix is the time axis and the horizontal axis
is the spatial axis.
Args:
speed_matrix: a Matrix containing spatial-temporal speed data for a network
seq_len: length of input sequence
pred_len: length of predicted sequence
Returns:
Training dataloader
Testing dataloader
"""
df_in=df_input.copy()
assert set([item[0] for item in df_in.index.tolist()])==set(subject_index_in)
# subject_index=[(item[0], item[1]) for item in df_in.index.tolist()] #select the subject_id and hadm_id
subject_index=sorted(df_in.index.tolist()) #select the subject_id, hadm_id, and hours_in
subject_index=sorted(subject_index, key=lambda x: subject_index_in.index(x[0])) #now it is in the order of the subject_index_in
#masked data
masked_df=pd.notna(df_in)
masked_df=masked_df.apply(pd.to_numeric)
#we can fill in the missing values with any number now (they get multiplied out to be zero)
df_in=df_in.fillna(0)
#time since last measurement
time_index=None
if not(time_index):
time_index='hours_in'
index_of_hours=df_in.index.names.index(time_index)
time_in=[item[index_of_hours] for item in df_in.index.tolist()]
time_df=df_in.copy()
for col in tqdm(time_df.columns.tolist()):
mask=masked_df[col].values
time_df[col]=time_since_last(time_in, mask)
time_df=time_df.fillna(0)
#last observed value
X_last_obsv_df=df_in.copy()
# do the mean imputation for only the first hour
columns=X_last_obsv_df.columns.tolist()
subset_data=X_last_obsv_df.loc[(slice(None), slice(None), 0), columns]
subset_data=subset_data.fillna(pd.DataFrame(np.mean(train_means, axis=1).reshape(1, -1), columns=columns).mean()) #replace first values with the mean of the whole row (not sure how original paper did it, possibly just fill with zeros???)
#replace first hour data with the imputed first hour data
replace_index=subset_data.index.tolist()
X_last_obsv_df.loc[replace_index, columns]=subset_data.values
X_last_obsv_df=X_last_obsv_df.fillna(0)
# now it is safe for forward fill
#forward fill the rest of the sorted data
X_last_obsv_df=X_last_obsv_df.loc[subject_index,:]
X_last_obsv_df=X_last_obsv_df.fillna(method='ffill')
gender=df_in.loc[(subject_index_in, slice(None), 0), 'F'].values.ravel()
ethnicity=df_in.loc[(subject_index_in, slice(None), 0), ['asian', 'black','hispanic','white', 'other']].values
#one hot encode ethnicity
ethnicity=np.argmax(ethnicity, axis=1).ravel()
# collect matrices into 3d numpy arrays
measurement_data=np.swapaxes(flattened_to_sequence(df_in.loc[subject_index, :])[0], 1,2)
X_last_obsv_data=np.swapaxes(flattened_to_sequence(X_last_obsv_df.loc[subject_index, :])[0], 1,2)
mask_data=np.swapaxes(flattened_to_sequence(masked_df.loc[subject_index, :])[0], 1,2)
time_data=np.swapaxes(flattened_to_sequence(time_df.loc[subject_index, :])[0], 1,2)
measurement_data=torch.from_numpy(measurement_data.astype(np.float32))
X_last_obsv_data=torch.from_numpy(X_last_obsv_data.astype(np.float32))
mask_data=torch.from_numpy(mask_data.astype(np.float32))
time_data=torch.from_numpy(time_data.astype(np.float32))
label= torch.as_tensor(y.astype(np.long))
ethnicity=torch.as_tensor(ethnicity.astype(np.long))
gender=torch.as_tensor(gender.astype(np.long))
if ethnicity_gender:
#optional to include for more complex model designs
train_dataset = utils.TensorDataset(measurement_data, X_last_obsv_data, mask_data, time_data, label, ethnicity, gender)
else:
train_dataset = utils.TensorDataset(measurement_data, X_last_obsv_data, mask_data, time_data, label)
dataloader = utils.DataLoader(train_dataset, batch_size = BATCH_SIZE, shuffle=shuffle, drop_last = drop_last)
return dataloader
def create_rnn(seqlen, n_features, hidden_layer_size, optimizer, activation, dropout, recurrent_dropout, recurrent_unit):
"""
Create RNN model in external function with sklearn style API
"""
model=rnn_tf2(input_shape=(seqlen,n_features), hidden_layer_size=hidden_layer_size, modeltype=recurrent_unit, activation=activation, input_dropout=recurrent_dropout, output_dropout=dropout, optimizer=optimizer)
return model
# class MLP_large(nn.Module):
# def __init__(self, in_size):
# super().__init__()
# self.feature_extractor = nn.Sequential(
# nn.Linear(in_size, 1000),
# nn.Dropout(p=0.5),
# nn.ReLU(),
# nn.Linear(1000, 500),
# nn.Dropout(p=0.5)
# )
# self.classifier = nn.Sequential(
# nn.Linear(500, 200),
# nn.Dropout(p=0.5),
# nn.ReLU(),
# nn.Linear(200, 100),
# nn.Dropout(p=0.5),
# nn.ReLU(),
# nn.Linear(100, 2),
# nn.Softmax(dim=1)
# )
# def forward(self, x):
# fe = self.feature_extractor(x)
# return self.classifier(fe)
# class MLP_small(nn.Module):
# def __init__(self, in_size):
# super().__init__()
# self.feature_extractor = nn.Sequential(
# nn.Linear(in_size, 500),
# nn.Dropout(p=0.5),
# nn.ReLU(),