-
Notifications
You must be signed in to change notification settings - Fork 1
/
run_model.py
2811 lines (2297 loc) · 145 KB
/
run_model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
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
"""
"""
import torch, torch.optim, torch.nn as nn, torch.nn.functional as F, torch.nn.init as init
from torch.utils.data import DataLoader, Dataset, RandomSampler, SubsetRandomSampler
from radam import RAdam
try:
from apex import amp
except ImportError:
amp=None
from GRUD import GRUD
from models import *
from constants import *
import os
from tqdm import tqdm
import pickle
import json
import re
import sys
import glob
import gc
import pandas as pd
import numpy as np
import random
import sklearn.metrics
from sklearn.metrics import roc_auc_score
from copy import deepcopy
from itertools import repeat
from multiprocessing import Pool
import time
import traceback
from collections import Counter
from datetime import date, timedelta
from prospective_set_up import get_retro
from torch.utils.data.dataloader import default_collate
# This fixed the andata 0 received issue, pytorch constructed this strategy to deal with filesystems with a limit on the number of open files, see https://pytorch.org/docs/stable/multiprocessing.html for downsides of using this strategy over the default, etc.
torch.multiprocessing.set_sharing_strategy('file_system')
def fast_lags(df, num_days, diff=False, ldiff=False):
holder = []
cidx = df[('idx','cidx')]
df = df.drop(columns=[('idx','cidx')])
for ll in np.arange(num_days)+1:
tmp_ll = df.shift(ll)
tmp_ll.columns = pd.MultiIndex.from_frame(tmp_ll.columns.to_frame().assign(df_type=str(ll)+'days_ago'))
tmp_ll.insert(0,('idx','cidx'),cidx)
tmp_ll.loc[tmp_ll[('idx','cidx')] <= ll] = np.NaN
tmp_ll.drop(columns=[('idx','cidx')],inplace=True)
if diff:
tmp_ll = df.values - tmp_ll
if ldiff:
tmp_ll = np.log((df.values+1) / (tmp_ll+1))
holder.append(tmp_ll)
tmp_ll = pd.concat(holder,1)
tmp_ll = pd.concat([df, tmp_ll],1)
return tmp_ll
def load_data(data_dir, regular=True, load_baseline=True, load_activity=True, load_survey=True, only_healthy=False, fname=None, verbose=False):
"""
"""
if fname is None:
f_pattern = '_daily_data_' + 'regular'*regular +'irregular'*(not(regular)) + '.hdf'
fnames = [f for f in os.listdir(data_dir) if f.endswith(f_pattern)]
assert len(fnames) <= 1, "More than one file matches pattern, unsure which to load"
assert len(fnames) > 0, "No file matched the pattern"
fname = fnames[0]
fname=os.path.join(data_dir, fname)
assert os.path.exists(fname), fname
if not(os.path.exists(fname)):
fname='all_daily_data.hdf'
fname=os.path.join(data_dir, fname)
assert os.path.exists(fname), fname
dfs={}
if load_baseline:
if verbose: print("loading baseline")
dfs['baseline']=pd.read_hdf(fname, 'baseline')
if load_activity:
if verbose: print("loading activity")
dfs['activity']=pd.read_hdf(fname, 'activity')
if load_survey:
if verbose: print("loading survey")
dfs['survey']=pd.read_hdf(fname, 'survey')
return dfs
def apply_limits(dfs, limit_df):
"""
Apply date limits in limit_df to all data in dfs
"""
limit_df = limit_df.set_index('participant_id')
out_dfs={}
for k, v in dfs.items():
if 'date' in v.index.names:
# apply the limits per participant
# multiindex slicing with date
out_dict={k:v.groupby('participant_id', group_keys=False).apply(lambda x: x.loc[(x.index.get_level_values('date')>=limit_df.loc[x.name, 'study_start_date'])
& (x.index.get_level_values('date')<=limit_df.loc[x.name, 'study_end_date'])])}
out_dfs.update(out_dict)
else:
out_dfs.update({k:v})
return out_dfs
def only_healthy(dfs, args):
"""
Return a new df with only the observations before the first positive
occurence of target.
Assumes data is in the format as read in by the load_data function above.
"""
result_df ={}
main_target = args.target[0]
tmp = dfs['survey'].reset_index(['date'])
tmp2 = pd.DataFrame.join(tmp[['date']], tmp[tmp[main_target] == 1].groupby('participant_id')[['date']].transform(min).reset_index().drop_duplicates().set_index('participant_id'), rsuffix='_min')
result_df['survey'] = dfs['survey'].reset_index(['date'])[(tmp2['date'] < tmp2['date_min'])].set_index(['date'], append=True)
result_df['activity'] = dfs['activity'].reset_index(['date'])[(tmp2['date'] < tmp2['date_min'])].set_index(['date'], append=True)
result_df['baseline'] = dfs['baseline']
return result_df
def write_results(args, scores, dataloader, istestset=True, participant_order=None):
csv_suffix = '_' + 'val'*(not(istestset)) + 'test'*istestset + 'set_results'+'.csv'
wpath = os.path.join(args.output_dir, args.target[0] + csv_suffix)
if isinstance(scores, pd.DataFrame):
print('Writing DataFrame')
scores = scores.reset_index()
scores.to_csv(wpath,index=False)
return
if not isinstance(scores, dict):
#If scores is not a dict then assume there is a single target
tmp = {}
# not all test participants are sampled.
if participant_order is None:
p = dataloader.dataset.participants
else:
p = participant_order
tmp[args.target[0]] = dataloader.dataset.outcomes[args.target[0]].sort_index().reindex(p, level='participant_id')
scores=np.concatenate([l.ravel() for l in scores], axis=0)
score_key = args.target[0]+'_score'
tmp[score_key] = pd.Series(scores)
# get the thresholds (or apply them
if istestset:
#load and check thresholds
if os.path.exists( os.path.join( args.output_dir, 'thresholds_activity.json')):
with open(os.path.join( args.output_dir, 'thresholds_activity.json')) as f:
threshold = json.load(f)
# apply this to the data and get the scores.
for k, v in threshold.items():
tmp[args.target[0]+'_pred_'+k] = np.asarray(scores >= float(v) ).astype(np.int32)
else:
# if this is validation set, and valid start/valid end date are defined, we must subselect those dates.
if args.validation_start_date is not None:
keep_inds = pd.to_datetime(tmp[args.target[0]].index.get_level_values('date'))>=args.validation_start_date
tmp[args.target[0]] = tmp[args.target[0]].loc[keep_inds , :]
# If keep_inds is the same length as the scores then the scores were not filtered prior to passing them to this function so remove the extra dates now.
if tmp[score_key].shape[0] == keep_inds.shape[0]:
tmp[score_key] = tmp[score_key].loc[keep_inds]
if args.validation_end_date is not None:
keep_inds = pd.to_datetime(tmp[args.target[0]].index.get_level_values('date'))<=args.validation_end_date
tmp[args.target[0]] = tmp[args.target[0]].loc[keep_inds, :]
if tmp[score_key].shape[0] == keep_inds.shape[0]:
tmp[score_key] = tmp[score_key].loc[keep_inds]
threshold={}
fpr, tpr, thresholds = sklearn.metrics.roc_curve( tmp[args.target[0]], tmp[score_key])
# 98% specificity
specificity=1-fpr
for spec in [0.98, 0.95]:
target_specificity = min(specificity[specificity>=spec])
# index of target fpr
index = list(specificity).index(target_specificity)
threshold['{}_spec'.format(int(spec*100))] = thresholds[index]
# 98% sensitivity
target_tpr = min(tpr[tpr>=0.98])
# index of target fpr
index = list(tpr).index(target_tpr)
threshold['98_sens'] = thresholds[index]
# 70% sensitivity
target_tpr = min(tpr[tpr>=0.7])
# index of target fpr
index = list(tpr).index(target_tpr)
threshold['70_sens'] = thresholds[index]
# 50% sensitivity
target_tpr = min(tpr[tpr>=0.5])
# index of target fpr
index = list(tpr).index(target_tpr)
threshold['50_sens'] = thresholds[index]
# threshold to json
with open(os.path.join(args.output_dir, 'thresholds_activity.json'), 'w') as f:
f.write(json.dumps({k:str(v) for k,v in threshold.items()}))
for k, v in threshold.items():
tmp[args.target[0]+'_pred_'+k] = np.asarray(tmp[score_key] >= float(v) ).astype(np.int32)
tmp[score_key] = tmp[score_key].values
#TODO: 'ili_pred_98_spec has not been the same length as scores after filtering by time for the validation set
pd.DataFrame(tmp).to_csv(wpath)
else:
tmp = dataloader.dataset.outcomes[list(args.target)].copy(deep=True).sort_index()
for k in scores.keys():
tmp.insert(len(tmp.columns), k + '_score', scores[k])
# get/load thresholds
if istestset:
#load and check thresholds
if os.path.exists( os.path.join( args.output_dir, k+'thresholds_activity.json')):
with open(os.path.join( args.output_dir, k+'thresholds_activity.json')) as f:
threshold = json.load(f)
# apply this to the data and get the scores.
for k2, v in threshold.items():
tmp[k+'_pred_'+k2] = np.asarray(scores >= float(v) ).astype(np.int32)
else:
# if this is validation set, and valid start/valid end date are defined, we must subselect those dates.
if args.validation_start_date is not None:
tmp = tmp.loc[tmp.index.get_level_values('date')>=args.validation_start_date, :]
if args.validation_end_date is not None:
tmp = tmp.loc[tmp.index.get_level_values('date')<=args.validation_end_date, :]
threshold={}
fpr, tpr, thresholds = sklearn.metrics.roc_curve( tmp[k].values, tmp[k+'_score'].values)
# specificity thresholds
specificity=1-fpr
for spec in [0.98, 0.95]:
target_specificity = min(specificity[specificity>=spec])
# index of target fpr
index = list(specificity).index(target_specificity)
threshold['{}_spec'.format(spec*100)] = thresholds[index]
# 98% sensitivity
target_tpr = min(tpr[tpr>=0.98])
# index of target fpr
index = list(tpr).index(target_tpr)
threshold['98_sens'] = thresholds[index]
# 70% sensitivity
target_tpr = min(tpr[tpr>=0.7])
# index of target fpr
index = list(tpr).index(target_tpr)
threshold['70_sens'] = thresholds[index]
# 50% sensitivity
target_tpr = min(tpr[tpr>=0.5])
# index of target fpr
index = list(tpr).index(target_tpr)
threshold['50_sens'] = thresholds[index]
# threshold to json
with open(os.path.join(args.output_dir, k+'thresholds_activity.json'), 'w') as f:
f.write(json.dumps({k2:str(v) for k2,v in threshold.items()}))
for k2, v in threshold.items():
tmp[k+'_pred_'+k2] = np.asarray(scores >= float(v) ).astype(np.int32)
tmp.to_csv(wpath)
def resample_fairly(participants, dfs, sample_col='ili'):
"""
increase the occurence of participants based on their ILI incidenc, week, and region.
Inputs:
participants (list): list of the participant ids to be involved.
dfs (dict): all of the dataframes from load_data
Returns:
(list): list of the participants upsampled.
"""
idx=pd.IndexSlice
# we want to balance interaction between week and region
region_dict = {'Northeast': ['CT', 'ME', 'MA', 'NH', 'RI', 'VT', 'NJ', 'NY', 'PA'],
'Midwest': ['IN', 'IL', 'MI', 'OH', 'WI', 'IA', 'KS', 'MN', 'MO', 'NE', 'ND', 'SD'],
'South': ['DE', 'DC', 'FL', 'GA', 'MD', 'NC', 'SC', 'VA', 'WV', 'AL', 'KY', 'MS', 'TN', 'AR', 'LA', 'OK', 'TX', 'PR'],
'West': ['AZ', 'MT', 'CO', 'ID', 'NM', 'UT', 'NV', 'WY', 'AK', 'CA', 'HI', 'OR', 'WA']}
region_dict2 = {item: key for key, value in region_dict.items() for item in value}
baseline_df = dfs['baseline'].copy()
print('converting states')
baseline_df['region'] =baseline_df['state'].replace(region_dict2)
baseline_df
df=dfs['survey'].copy()
# df['weekofyear']=df.index.get_level_values('date').weekofyear
if 'weekofyear' not in df.columns:
df['weekofyear']=df.index.get_level_values('date').isocalendar().week
# get the number of occurences for each person in the training data
participant_df = df.groupby('participant_id').apply(lambda x: x[sample_col].gt(x[sample_col].shift()).cumsum().max() + x[x.index.get_level_values('date') == x.index.get_level_values('date').min()][sample_col]) # todo, just do this once, them multiply by counts in list of participants
print('grouping participant_id and weekofyear')
tmp_df = df[['weekofyear', sample_col]].groupby(['participant_id', 'weekofyear']).max()
tmp_df = tmp_df.join(baseline_df['region'], on='participant_id', how='left')
ineligible_upsamples = tmp_df.loc[~tmp_df['region'].isin(region_dict.keys())].index.get_level_values('participant_id').tolist()
ineligible_downsamples = []
max_week_df = tmp_df.groupby(['weekofyear', 'region']).sum()
region_weeks = zip(max_week_df.index.get_level_values('region'), max_week_df.index.get_level_values('weekofyear'), max_week_df[sample_col])
region_weeks=sorted(region_weeks, key=lambda x: x[2])
print("maximum week ", region_weeks[-1])
# get the participants in the max week so that we don't upsample them.
max_week_participants = list(set(tmp_df.loc[(tmp_df.index.get_level_values('weekofyear')==region_weeks[-1][1])\
&(tmp_df['region']==region_weeks[-1][0])\
&(tmp_df[sample_col]==1), :].index.get_level_values('participant_id')))
region_weeks = [item for item in region_weeks if item[2]>10] # skip the weeks where there are few cases/surveys
while len(region_weeks)>1:
print(len(region_weeks))
time_old = time.time()
time_older=time.time()
amplifier = pd.Series(Counter(participants)) # get the number of unique instances for each participant
amplifier.index.name='participant_id'
amplifier.name='multiplier'
tmp_df2 = tmp_df.join(amplifier, how='left', on='participant_id')
tmp_df2.loc[:, 'ili_multiplier'] = tmp_df2[sample_col]*tmp_df2['multiplier']
# sum all the participants with ILI in a given week+region
max_week_df = tmp_df2.groupby(['weekofyear', 'region']).sum()
# remove the data we've already covered
max_week_df = max_week_df.loc[[(item[1], item[0]) for item in region_weeks]]
# make it into a tuple
region_weeks = zip(max_week_df.index.get_level_values('region'), max_week_df.index.get_level_values('weekofyear'), max_week_df['ili_multiplier'])
region_weeks=sorted(region_weeks, key=lambda x: x[2])
# now we are always popping the minimum region/week combo
region_week=region_weeks.pop(-2)
print(region_week)
if region_week[2]==0:
# there are no ili incidence this week
continue
participant_df_sample = participant_df.loc[participants].groupby('participant_id').sum() # this reflects their prevalence in oversampleing.
# particpants not in max_region_week or who have already been upsamples get upsampled
eligible_samples = tmp_df2.loc[(tmp_df2.index.get_level_values('weekofyear')==region_week[1])\
&(tmp_df['region']==region_week[0])\
&(~tmp_df2.index.get_level_values('participant_id').isin( max_week_participants+ineligible_upsamples))\
&(tmp_df2['ili_multiplier']==1), :]
if len(eligible_samples)==0:
print(region_week)
continue
raise Exception(f'ran out of eligible samples for week {region_week[1]} and region {region_week[0]}')
# sample participants based on the inverse of their frequency in other weeks
weights=(1/participant_df_sample.loc[participant_df_sample.index.isin(eligible_samples.index.get_level_values('participant_id'))].values)/\
sum( 1/participant_df_sample.loc[ participant_df_sample.index.isin(eligible_samples.index.get_level_values('participant_id'))].values)
# finally add the upsampled participants
participants += eligible_samples.sample(n=int(region_weeks[-1][2]-region_week[2]), weights=weights, replace=True).index.get_level_values('participant_id').tolist()
# now remove samples from elibile samples
ineligible_upsamples += eligible_samples.index.get_level_values('participant_id').tolist()
amplifier = pd.Series(Counter(participants)) # get the number of unique instances for each participant
amplifier.index.name='participant_id'
amplifier.name='multiplier'
tmp_df2 = tmp_df.join(amplifier, how='left', on='participant_id')
tmp_df2.loc[:, 'ili_multiplier'] = tmp_df2[sample_col]*tmp_df2['multiplier']
# add some checks
max_week_df = tmp_df2.loc[idx[participants, :], :].groupby(['weekofyear', 'region']).sum()
region_weeks = zip(max_week_df.index.get_level_values('region'), max_week_df.index.get_level_values('weekofyear'), max_week_df['ili_multiplier'])
region_weeks=sorted(region_weeks)
print(region_weeks)
# show the mean by region
for region in sorted(list(set(max_week_df.index.get_level_values('region')))):
print(region, 'mean: ', np.mean([item[2] for item in region_weeks if item[0]==region]), 'std: ', np.std([item[2] for item in region_weeks if item[0]==region]))
# show the mean by week
for weekofyear in sorted(list(set(max_week_df.index.get_level_values('weekofyear')))):
print(weekofyear, 'mean: ', np.mean([item[2] for item in region_weeks if item[1]==weekofyear]), 'std: ', np.std([item[2] for item in region_weeks if item[1]==weekofyear]))
return participants
class ILIDataset(Dataset):
def __init__(self, dfs, args, full_sequence=False, feat_subset=False, participants=None):
"""
feat_subset: boolean, use only the subset of features used by Raghu
which improved performance in the xgboost and ridge regression models
in the 'measurement' dataframe.
"""
self.max_seq_len=args.max_seq_len
self.numerics = dfs['activity']
self.statics = dfs['baseline']
self.outcomes = dfs['survey']
self.feat_subset = feat_subset
self.subset = ['heart_rate_bpm', 'walk_steps', 'sleep_seconds',
'steps__rolling_6_sum__max', 'steps__count',
'steps__sum', 'steps__mvpa__sum', 'steps__dec_time__max',
'heart_rate__perc_5th', 'heart_rate__perc_50th',
'heart_rate__perc_95th', 'heart_rate__mean',
'heart_rate__stddev', 'active_fitbit__sum',
'active_fitbit__awake__sum', 'sleep__asleep__sum',
'sleep__main_efficiency', 'sleep__nap_count',
'sleep__really_awake__mean',
'sleep__really_awake_regions__countDistinct']
if args.no_imputation:
self.activity_sub_df = 'measurement_noimp'
else:
self.activity_sub_df = 'measurement'
print(self.activity_sub_df, '*'*30)
# Using np.unique returning the indices to preserve the order the participants are in the original
# self.participants=list(np.unique(dfs['baseline'].index.get_level_values('participant_id')))
#self.participants=np.unique(dfs['baseline'].index.get_level_values('participant_id')).tolist()
if participants is None:
# only resample for training data
self.participants = list(np.unique(dfs['survey'].index.get_level_values('participant_id')))
else:
self.participants = participants
self.full_sequence=full_sequence
if args.weekofyear:
ACTIVITY_COLS.append('weekofyear')
self.ACTIVITY_COLS = ACTIVITY_COLS
self.cat_mask_measure_time=False
if 'modeltype' in vars(args).keys():
if args.modeltype=='gru_simple':
# input('running with concatenation')
self.cat_mask_measure_time=True
def __len__(self):
return len(self.participants)
def __getitem__(self, item):
"""
"""
participant = self.participants[item]
# print(type(participant))
idx = pd.IndexSlice
# get the data for these participants
# print('ind:', self.numerics.index.names)
# print('cols:', self.numerics.columns.names)
time_df = self.numerics.loc[idx[participant, :], idx['time', :]].values
if self.feat_subset:
measurement_df = self.numerics.loc[idx[participant, :],
idx[self.activity_sub_df, self.subset]].values
measurement_z_df = self.numerics.loc[idx[participant, :],
idx['measurement_z', self.subset]].values
else:
measurement_df = self.numerics.loc[idx[participant, :],
idx[self.activity_sub_df, self.ACTIVITY_COLS]].values
measurement_z_df = self.numerics.loc[idx[participant, :],
idx['measurement_z', self.ACTIVITY_COLS]].values
mask_df =self.numerics.loc[idx[participant, :], idx['mask', self.ACTIVITY_COLS]].values.astype(np.int32)
# get the outcomes
ili_outcomes=self.outcomes.loc[idx[participant, :], 'ili'].apply(int).values
ili_24_outcomes=self.outcomes.loc[idx[participant, :], 'ili_24'].apply(int).values
ili_48_outcomes=self.outcomes.loc[idx[participant, :], 'ili_48'].apply(int).values
covid_outcomes=self.outcomes.loc[idx[participant, :], 'covid'].apply(int).values
covid_24_outcomes=self.outcomes.loc[idx[participant, :], 'covid_24'].apply(int).values
covid_48_outcomes=self.outcomes.loc[idx[participant, :], 'covid_48'].apply(int).values
fever_outcomes=self.outcomes.loc[idx[participant, :], 'symptoms__fever__fever'].apply(int).values
if 'loss_mask' in self.outcomes.columns:
loss_mask=self.outcomes.loc[idx[participant, :], 'loss_mask'].apply(int).values
else:
loss_mask=None
return_dict = {'measurement_z':measurement_z_df, 'measurement':measurement_df, 'mask':mask_df, 'time':time_df, 'ili':ili_outcomes, 'ili_24': ili_24_outcomes, 'ili_48':ili_48_outcomes, 'covid':covid_outcomes, 'covid_24':covid_24_outcomes, 'covid_48': covid_48_outcomes, 'symptoms__fever__fever':fever_outcomes, 'obs_mask':np.ones(len(measurement_df))}
if loss_mask is not None:
return_dict.update({'loss_mask':loss_mask})
assert sum(return_dict['obs_mask'])>0
if self.full_sequence:
return_dict = {k:torch.tensor(v).float() for k,v in return_dict.items()}
if self.cat_mask_measure_time:
return_dict.update({'measurement':
torch.cat((return_dict['measurement'], return_dict['mask'], return_dict['time']), dim=-1)})
return return_dict, participant
# pad them to the maximum sequence length
if len(time_df)>self.max_seq_len:
# make sure 50% of the time there is a 1 in the data...
# find minimum index of 1 in labels
min_index= list(return_dict['ili']).index(1) if sum(return_dict['ili'])>0 else 0
random_val= random.random() if sum(return_dict['ili'])>0 else 1 # this is mostly not the case, but to be sure we can remove patients without ILI in the start.
if random_val<0.5:
# includes a 1
assert max(0, min_index-self.max_seq_len-1)<(len(time_df)-self.max_seq_len), (max(0, min_index-self.max_seq_len-1),(len(time_df)-self.max_seq_len))
random_start = random.randint(max(0, min_index-self.max_seq_len-1), len(time_df)-self.max_seq_len)
# sample and crop
max_time = min(random_start+self.max_seq_len, len(return_dict['ili']))
return_dict={k:v[random_start:max_time] for k,v in return_dict.items()}
else:
# does not include a 1
random_start = random.randint(0, min_index-1) if (min_index-1 )>0 else 0
# sample and crop
max_time = min(random_start+self.max_seq_len, len(return_dict['ili']))
return_dict={k:v[random_start:max_time] for k,v in return_dict.items()}
if len(return_dict['measurement'])<self.max_seq_len:
# pad to length
for k, v in return_dict.items():
# print(k)
shape=list(v.shape)
shape[0]=self.max_seq_len
# print(v)
obj = np.zeros(shape)
obj[:len(v)]=v
# print(v)
return_dict[k]=obj
# for k,v in return_dict.items():
# print(k, v.dtype)
return_dict = {k:torch.tensor(v).float() for k,v in return_dict.items()}
# for item in return_dict.values():
# assert len(item)==self.max_seq_len, print(len(item), self.max_seq_len)
if self.cat_mask_measure_time:
return_dict.update({'measurement':
torch.cat((return_dict['measurement'], return_dict['mask'], return_dict['time']), dim=-1)})
return return_dict, participant
# Solution on Pytorch forum from justusschock for a custom collate function
# which will return an id with each batch.
def id_collate(batch):
new_batch = []
ids = []
for _batch in batch:
new_batch.append(_batch[:-1])
ids.append(_batch[-1])
return default_collate(new_batch), ids
def merge_fn(batch):
"""
Train/Val DataLoader collate_fn (to merge the different datasets into a batch with pack_sequence)
"""
batch = sorted(batch, key=lambda x: -len(x[0])) #sort by length of sequence
data, target = zip(*batch)
batch = sorted(batch, key=lambda x: -len(x[0]['measurement']))
ids = [b[-1] for b in batch]
new_batch = {k: [item[0][k] for item in batch] for k in batch[0][0].keys()}
new_batch = {k : nn.utils.rnn.pack_sequence(v) for k, v in new_batch.items()}
return new_batch, ids
def weight_init(m):
if isinstance(m, nn.Linear):
nn.init.xavier_uniform_(m.weight.data)
if m.bias is not None:
torch.nn.init.zeros_(m.bias)
def apply_standard_scaler(dfs, args, scaler=None):
"""
apply sklearn standard scaler.
Takes args to know what sub dataframe to use.
"""
if args.no_imputation:
sub_df = 'measurement_noimp'
else:
sub_df = 'measurement'
idx=pd.IndexSlice
if scaler is not None:
assert isinstance(scaler, dict), print('Expected a dict for arguement scaler')
else:
print(set(sorted(dfs['activity'].loc[:, idx[sub_df, :]].columns.tolist()))-set(dfs['activity'].loc[:, idx[sub_df, :]].sample(5000).mean().index.tolist()))
scaler={'mean': dfs['activity'].loc[:, idx[sub_df, :]].sample(5000).mean().values,
'std': dfs['activity'].loc[:, idx[sub_df, :]].sample(5000).std().values,
}
# apply to measurement column in X and X_ffilled
assert scaler['mean'][np.newaxis, :].shape[1:] == scaler['std'][np.newaxis, :].shape[1:], print(scaler['mean'][np.newaxis, :].shape, scaler['std'][np.newaxis, :].shape[1:])
assert dfs['activity'].loc[:, idx[sub_df, :]].values.shape[1:] == scaler['std'][np.newaxis, :].shape[1:], print(dfs['activity'].loc[:, idx[sub_df, :]].values.shape, scaler['std'][np.newaxis, :].shape)
dfs['activity'].loc[:, idx[sub_df, :]] = (dfs['activity'].loc[:, idx[sub_df, :]].values - scaler['mean'][np.newaxis, :])/scaler['std'][np.newaxis, :]
return dfs, scaler
def cnn_lklhd(mus, Sigma, x):
"""
Helper function for cnn model, returns the loglikelihood for each observation using pytorchs logprob for multivariate gaussian distribution.
"""
loglklhds = []
for i in range(x.shape[0]):
dist = torch.distributions.MultivariateNormal(mus[i, :], scale_tril=Sigma[i, :, :])
loglklhds.append(dist.log_prob(x[i,:]).unsqueeze(dim=0))
return torch.cat(loglklhds, axis=0)
def old_cnn_lklhd(mus, logstds, x, k):
"""
Helper function for cnn model, returns the loglikelihood for a observation given the
parameters returned by the 1dcnn model.
TODO: Should this function be put into the cnn model class, or it's own file?
"""
loglklhds = []
stds = torch.exp(logstds)
for i in range(x.shape[0]):
Sigma = torch.diag(stds[i,:]**2)
detSigma = torch.prod(stds[i,:]**2) + 1e-20
dif = x[i:(i+1),:] - mus[i:(i+1), :]
difT = torch.transpose(dif, 0, 1)
invSigma = torch.inverse(Sigma)
# Tested the pytorch implementation I'm getting the same loglikelihoods with
# my calculation.
#dist = torch.distributions.MultivariateNormal(mus, Sigma)
#torch_lklhd = dist.log_prob(x)
print('Det(Sigma): ' + str(detSigma))
min_var = torch.min(stds[i,:]**2).detach().numpy()
print('Min_var: ' + str(min_var))
print('which_is_min: ' + str(np.where((stds[i,:]**2).detach().numpy() == min_var)))
assert detSigma != 0, 'Singular covariance matrix'
left_term = torch.log(detSigma)
#Note for mid_term the transpose is backwards, because of
# the shape of x being (batch, features).
mid_term = torch.mm(torch.mm(dif,invSigma), difT)
right_term = k*torch.log(torch.tensor(2*math.pi))
loglklhds.append(-0.5*(left_term + mid_term + right_term))
return torch.cat(loglklhds, axis=0).squeeze(dim = 1)
def add_shifts(inp, days_to_shift):
""" Using `days_ago` arguement to set number of past days to add to features"""
pid, df = inp
df = df.droplevel(0).sort_index() # Assumes it is of `datetype` type #pd.DatetimeIndex(df['date']))
keep_cols = df.columns
for day_shift in [(q, 'days_ago') for q in range(1, days_to_shift + 1)]:
tmp = df.loc[:, keep_cols].shift(day_shift[0])
tmp.columns = pd.MultiIndex.from_product([[str(day_shift[0])+day_shift[1]],
keep_cols.get_level_values('value').to_list()])
# tmp.columns = tmp.columns.set_levels([str(day_shift[0]) + day_shift[1]], level=0)
df = df.join(tmp, how='left')
df.index = pd.MultiIndex.from_product([[pid], df.index])
return df
def get_close_dates(df, time, time_col, time_delta, group_col=None, mask=None):
"""
Takes a dataframe, a date, a time delta, Series of time deltas or dataframe
with a column of time deltas, and a time column name, then it filters all
rows to only those close enough to the date by the time_delta in the
time_col of the df. time_delta can also be container of two elements
indicating a previous different acceptable length for before and after
time. Optionally it can take a group_col which will index a different time
per member of the group, the keys for the time object must be the group
names in the group_col. Also it can take a mask which will then drop
arbitrary dates which are close enough to time as well, mask times are
relative to time and must all fall within the time_delta bound. It's
assumed there is a time in the df except in the case where time has a
group_col, then if the group id does not have an entry in the time
dataframe it will return an empty dataframe with the same index and column
names as df.
df: pandas dataframe
time: pandas datetime or pandas dataframe
time_col: str, column name of df which is datetime type
time_delta: pandas timedelta or tuple of pandas timedelta
group_col: str, column name for the time dataframe to extract a datetime per group
mask: list of ints
"""
# First deal with if the group_col is a column or an index by reseting the index.
index_cols = list(df.index.names)
if group_col in index_cols:
index_cols.remove(group_col)
df = df.reset_index()
if not (group_col is None):
group = np.unique(df[group_col])
assert len(group) == 1, 'More than one value in df[group_col], might be df is not grouped or group_col is not the column grouped by'
group = group[0]
time = time[time[group_col] == group][time_col]
# Check that the group id is in the time dataframe, if not return an
# empty dataframe. This is a case in our experiments where a participant
# has no date of onset in the truncated dataframe, due to the change in
# timeframe, thus returning an empty dataframe is the correct output.
if len(time) == 0:
return df.set_index(index_cols).drop(columns=group_col, errors='ignore')[:0]
# Get separate bounds for the time_delta
if len(time_delta) == 2:
assert time_delta[0] <= time_delta[1], 'lesser time_delta must be smaller than upper time_delta'
lower_delta, upper_delta = time_delta
elif len(time_delta) == 1:
lower_delta = time_delta[0]
upper_delta = time_delta[0]
keep_date = pd.concat([df[time_col] - pd.to_datetime(t) for t in time], axis = 1).apply(lambda x: (x >= lower_delta) & (x <= upper_delta) & (~x.isin(mask)) ).any(axis = 1)
res_df = df.set_index(index_cols).drop(columns=group_col, errors='ignore')[keep_date.values]
return res_df
def boundary_helper(participant_id, recovery_dates, ili_diffs):
"""
A helper function to turn a list comprehension into something more readable.
Concats the maximum date when the ili_diffs is missing a recovery date,
because the event terminates after the dataframes maximum date.
"""
tmp_dict = {'participant_id':participant_id,
'date':ili_diffs.loc[participant_id].index.get_level_values('date').max()}
tmp_df = pd.DataFrame(tmp_dict, index=[0])
cur_recov_df = recovery_dates[recovery_dates['participant_id'] == participant_id]
return pd.concat([cur_recov_df, tmp_df], ignore_index=True)
def onset_recovery_diff(x):
"""
Only works on a Series, handles missing value occuring at the beginning and end of a pandas diff call, instead of returning NA, it will use the value that was there prior to the diff. ie, Series([1,2,3]) becomes Series([1,1,1]).
"""
x.index = x.index.droplevel('participant_id')
didx = pd.Series(x.index.get_level_values('date'))
diffed = x.reindex(pd.DatetimeIndex([didx.min() - pd.Timedelta('1d')] + didx.to_list() + [didx.max() + pd.Timedelta('1d')]), fill_value=0).diff()
return diffed
def create_lagged_data(dataloader, args, bound_events, use_features=None, target=['ili']):
"""
TODO: Not tested with target having length greater than 1...
Inputs:
dataloader (torch.utils.dataset.DataLoader): An instance of wrapped ILIDataset.
forecast_features (list): a list of column headings to restrict features to.
target: the objective feature.
Returns:
X (np.array): ??
y (np.array): ??
"""
assert isinstance(target, list), "target must be a list of target column names"
idx=pd.IndexSlice
# ILIDataset has attributes self.numerics, self.statics, self.outcomes, self.participants
measurement_col = 'measurement' + args.zscore*'_z' + args.no_imputation*'_noimp'
forecast_features = ['time'] + [str(q) + 'days_ago' for q in range(1, args.days_ago + 1)]
print(dataloader.dataset.numerics.loc[:, idx[measurement_col, :]].head())
if use_features is None:
#use_features = dataloader.dataset.numerics.columns.get_level_values('value').tolist()
use_features =dataloader.ACTIVITY_COLS # hard coded for safety
label_colz = ['ili', 'ili_24', 'ili_48', 'covid', 'covid_24', 'covid_48', 'symptoms__fever__fever', 'flu_covid', 'time_to_onset']
target_col = ('label', target[0])
# add measurement col?
forecast_features += [measurement_col] # add today's measurements as part of feature set
### Load survey dataframe (for ILI labels)
print('Loading survey data ...')
survey = dataloader.dataset.outcomes.copy()
survey = survey.sort_index()
if len(survey.columns.names)==1:
pass #target_col = target[0]
# survey.columns = pd.MultiIndex.from_product([['label'],survey.columns.tolist()])
if bound_events and not 'time_to_onset' in survey.columns:
# column orig_ili should be created if bound_events has been set, this is to preserve the original ili events for appropriate dropping of events too close together.
ili_diffs = survey['orig_ili'].groupby('participant_id').apply(onset_recovery_diff)
ili_diffs.index = ili_diffs.index.rename(['participant_id', 'date'])
assert len(target) == 1, 'TODO: not implemented for targets lists of length greater than 1.'
# Restricting all labels to near an ILI event.
t = 'ili'
# get onset dates for each participant which are far enough apart.
onset_dates = ili_diffs[ili_diffs == 1].reset_index()[['participant_id', 'date']]
onset_dates_diff = onset_dates.groupby('participant_id').diff()
is_first_onset_date = onset_dates_diff['date'].isnull()
# Get the recovery dates to ensure the next event is far enough away.
recovery_dates = ili_diffs[ili_diffs == -1].reset_index()[['participant_id', 'date']]
# This assert is probably extra, I think because of how diffs is defined there couldn't be any additional recovery dates when given a binary sequence, so it is really just double checking we got a binary sequence for ILI.
assert len([p for p in np.unique(ili_diffs.index.get_level_values('participant_id')) if not recovery_dates[recovery_dates['participant_id'] == p].shape[0] - onset_dates[onset_dates['participant_id'] == p].shape[0] in [-1, 0]]) == 0, 'The number of recovery dates and onset dates differs by more than one for some participants.'
recovery_dates = pd.concat([boundary_helper(p, recovery_dates, ili_diffs) if recovery_dates[recovery_dates['participant_id'] == p].shape[0] - onset_dates[onset_dates['participant_id'] == p].shape[0] != 0 else recovery_dates[recovery_dates['participant_id'] == p] for p in np.unique(ili_diffs.index.get_level_values('participant_id'))])
# length of events
event_lens = pd.concat([recovery_dates['participant_id'], recovery_dates['date'] - onset_dates['date'].values], axis=1, ignore_index=True)
event_lens = event_lens.rename(columns={0:'participant_id', 1:'length'})
# shift by one period
event_lens['length'] = event_lens['length'].shift()
onset_distance = pd.to_timedelta(min(args.bound_labels)*-1 + args.days_ago, 'd') + event_lens['length']
is_far_from_onset_date = onset_dates_diff['date'] >= onset_distance.reset_index(drop=True)
onset_dates = onset_dates[is_first_onset_date | is_far_from_onset_date]
#leave enough previous days for first day wanted to be in the bound to have all previous days worth of data.
larger_bounds = (args.bound_labels[0] - args.days_ago, args.bound_labels[1])
# final bound will restrict the dates to just the ones we want to make a prediction on and not keep the days necessary to fill the days ago columns.
final_bounds = (args.bound_labels[0], args.bound_labels[1])
final_indices = survey.groupby('participant_id').apply(get_close_dates, onset_dates, 'date', pd.to_timedelta(final_bounds, 'd'), 'participant_id', pd.to_timedelta(args.mask_labels, 'd')).index
#select down the survey dataframe to the appropriate dates.
survey = survey.groupby('participant_id').apply(get_close_dates, onset_dates, 'date', pd.to_timedelta(larger_bounds, 'd'), 'participant_id', pd.to_timedelta(args.mask_labels, 'd'))
elif bound_events:
# Use the time_to_onset column instead of calculating it. Survey has enough back data for the features to have 7 days worth of data.
survey = survey[(survey['time_to_onset'] >= min(args.bound_labels) - args.days_ago) & (survey['time_to_onset'] <= max(args.bound_labels)) & (~survey['time_to_onset'].isin(args.mask_labels))]
# final_indices will restrict to the dates we actually want to make predictions on.
final_indices = survey[(survey['time_to_onset'] >= min(args.bound_labels)) & (survey['time_to_onset'] <= max(args.bound_labels)) & (~survey['time_to_onset'].isin(args.mask_labels))].index
survey.columns = pd.MultiIndex.from_product([[target_col[0]], survey.columns]) # add multi-index columns to survey
activity = dataloader.dataset.numerics.loc[:, idx[measurement_col, use_features]]
activity = activity.loc[survey.index]
print('survey shape: %s' % (survey.shape,))
### Create day-shifted features - for a subset of 20 features
# print(len(use_features))
print('Using cores=', args.num_dataloader_workers)
print('Creating day-shifted dataset ...')
p = Pool(args.num_dataloader_workers)
out = pd.concat(p.starmap(add_shifts,
zip(activity.groupby('participant_id'),
repeat(args.days_ago))))
out.index.names = ['participant_id', 'date']
print('Shifted-features dataframe:', out.shape)
### Merge with day-level ILI labels and adding time features
out = out.join(survey.loc[:, idx[[target_col[0]], label_colz]], how='left')
# out['time', 'day_of_week'] = pd.Series(out.index.get_level_values(1)).dt.weekday.values
if args.weekofyear:
if ('time','weekofyear') not in out.columns.tolist():
print(out.columns.tolist())
# out['time', 'weekofyear'] = pd.Series(out.index.get_level_values(1)).dt.weekofyear.values # potentially remove this
out['time', 'weekofyear'] = pd.Series(out.index.get_level_values(1)).dt.isocalendar().week.astype(np.int32).values # potentially remove this
print('out shape: %s' % (out.shape,))
print('out columns: %s' % out.columns)
#filter out to have the final indices only, if bounding observations around events.
if bound_events:
out = out.loc[final_indices]
X = out.loc[:,idx[forecast_features, :]]
y = out.loc[:, target_col]
if args.resample:
participant_count= Counter(dataloader.dataset.participants)
sample_weight = [participant_count[item] for item in y.index.get_level_values('participant_id')]
else:
sample_weight=None
return X, y, sample_weight
def train_torch(model, train_dataloader, valid_dataloader, args):
"""
Train the models that require pytorch dataloader in a serperate function
"""
return
def get_latest_event_onset(dfs):
"""
input:
dfs (dict): a dict of pandas dataframes of the data.
Returns:
(list): a list of tuples of participant_id, and latest event onset date.
"""
df=dfs['survey'].copy()
df['ili_count'] = df['ili'].groupby('participant_id').apply(lambda x:x.rolling(2).apply(lambda y:y[0]<y[-1], raw=True).cumsum())
df['ili_count'] = df['ili_count'].fillna(0)
tmp_df = df['ili'].groupby('participant_id').first()
df = df.join(tmp_df, on=['participant_id'],how='left', rsuffix='_first')
# if it starts with 1, we also want to coutn it as a case.
df['ili_count']=df['ili_count']+df['ili_first']
df = df.loc[df.groupby('participant_id')['ili_count'].transform(max) ==df['ili_count']] # get only th maximum ili per participant
# get the onset dat for the maximum ili per participant
df = df.reset_index().loc[df.reset_index().groupby('participant_id')['date'].transform(min)==df.reset_index()['date']]
# get the index of the onset of the latest event for a partiicpant.
participant_ili_tuples = df.set_index(['participant_id', 'date']).index.tolist()
return participant_ili_tuples
def split_helper(participants, train_size=0.7, val_size=0.15, test_size=0.15):
assert (train_size + val_size + test_size) == 1, "split sizes don't add up to one"
random.shuffle(participants)
train_participants = participants[:int(0.7*len(participants))]
valid_participants = participants[int(0.7*len(participants)):int(0.85*len(participants))]
test_participants = participants[int(0.85*len(participants)):]
return train_participants, valid_participants, test_participants
def get_onset_dates(x, label_col):
"""
Get the first instance sick day for a participants label series, fixes case
where onset is the first day of the Series.
"""
didx = pd.Series(x.index.get_level_values('date'))
diff = x.droplevel(0).reindex(pd.DatetimeIndex([didx.min() - pd.Timedelta('1d')] + didx.to_list() + [didx.max() + pd.Timedelta('1d')]), fill_value=0).diff()
#drop the added dates to fix end point corner case for diff
diff = diff[1:-1]
onset_dates = x.droplevel(0)[(diff == 1).values]
return onset_dates
def change_labels(dataframe, relative_changes, label_column):
"""
Assumes the label in the dataloader is binary, and will then make the positive labels relative to the first label in each sequence of the positive class, in our case the date of onset for a disease.
dataframe : pandas dataframe with a binary label in the dataset.
relative_changes : list of values for labels relative to the first positive label which will be the new positive labels. ex: if old label column is [0 0 0 1 1 1 0 1] with relative change being (-1, 0, 1), then the output label column will be [0 0 1 1 1 0 1 1].
"""
onset_dates = dataframe[label_column].groupby('participant_id').apply(get_onset_dates, label_col=label_column)
# When the difference is greater than 0 the previous row must have been 0 indicating that it is a day of onset.
new_dataframe = dataframe
new_dataframe[label_column] = 0
for change in relative_changes:
date_offset = pd.to_timedelta(change, unit='d')
relative_dates = onset_dates.copy()
relative_dates = relative_dates.reset_index()
relative_dates['date'] = relative_dates['date'] + date_offset
relative_dates = relative_dates.set_index(['participant_id', 'date']).index
relative_dates = relative_dates[relative_dates.isin(new_dataframe.index)]
new_dataframe.loc[relative_dates] = 1
return new_dataframe
def restricted_float(s):
try:
f = float(s)
except ValueError:
raise argparse.ArgumentTypeError("{} not a floating-point literal".format(s))