-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysing.py
2166 lines (2149 loc) · 114 KB
/
mysing.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 numpy as np
import scipy
import operator
import matplotlib.pyplot;
matplotlib.pyplot.switch_backend('agg')
import seaborn as sns ; sns.set(style="ticks", color_codes=True)
import os
import csv
import pandas as pd
from scipy import stats
from sklearn.neighbors import KNeighborsRegressor
# from hmmlearn import hmm
import warnings
from sklearn.model_selection import cross_val_score
from babel.util import missing
from IPython.core.magics import pylab
from boto.ec2.cloudwatch import dimension
warnings.filterwarnings("ignore", category=DeprecationWarning)
from sklearn.externals import joblib
import sklearn
from scipy.optimize import linear_sum_assignment
import matplotlib.collections
import statsmodels.api as sm
from sklearn.decomposition import PCA
from statsmodels.genmod.generalized_estimating_equations import GEE
from statsmodels.genmod.cov_struct import (Exchangeable,
Independence,Autoregressive)
from statsmodels.genmod.families import Poisson
import statsmodels.formula.api as smf
from sklearn import linear_model
from sklearn import svm
import matplotlib.pyplot as plt
import math
from numpy import dual
import sys
# /Users/manisci/Library/Mobile Documents/com~apple~CloudDocs/Documents/research/Winbraek18/Hmmimp/
sys.path.insert(0, '/Users/manisci/Library/Mobile Documents/com~apple~CloudDocs/Documents/research/Winbraek18/Hmmimp/')
# sys.path.insert(0, '/Users/manisci/Documents/research/Winbraek18/Hmmimp/')
import get_seq_statescont
import init_gaussian
np.set_printoptions(precision=3,suppress=True)
def swapaxes(matrix):
# matrix = np.swapaxes(matrix, 0, -1)
matrix = np.swapaxes(matrix, -1, -2)
return matrix
def returnoutputvar(filename):
content = open(filename, 'r').read()
return content.split()
def removeinvalidptsfromdict(diction,allmiss):
'''
removing the invalid patients and coordinating the rest of patients to have the correct index
'''
for ind in range(len(allmiss)-1):
diction.pop(allmiss[ind])
for val in sorted(diction.keys()):
if val in range(allmiss[ind] +1,allmiss[ind+1]):
diction[val - (ind+1)]= diction[val]
diction.pop(val)
diction.pop(allmiss[-1])
for val in sorted(diction.keys()):
if val > allmiss[-1]:
diction[val - len(allmiss)]= diction[val]
diction.pop(val)
return diction
def main():
'''
Runs the HMM model on a single combined or original ICU type.
'''
# Uses already available files to extract values of these normal medical meterics
saps = returnoutputvar("saps.txt")
apache = returnoutputvar("apache.txt")
mpm =returnoutputvar("mpm.txt")
sofa = returnoutputvar("sofa.txt")
recid = returnoutputvar("recid.txt")
with warnings.catch_warnings():
warnings.filterwarnings("ignore",category=DeprecationWarning)
# Change current directory to train folder to read the files
os.chdir("..")
os.chdir(os.path.abspath(os.curdir) + "/train")
# Extracting top 7 features mentioned in the paper
(wholefeat,featmtrx1,featmtrx2,featmtrx3,featmtrx4,\
featfirst1,featfirst2,featfirst3,featfirst4,\
featsecond1,featsecond2,featsecond3,featsecond4,\
paticutypedictindex, heartratedict,ages,genders,WBCdict,tempdict,GCSdict,glucosedict,NIDSdict,urinedict,AVGmeanchangefeats,AVGmedianchangefeats,recidees) = xtracttopfeat()
# Extracting length of stay of patients
(los,los1,los2,los3,los4,invalids,losrecids) = xtrlenofstay(paticutypedictindex)
# dealing with patients who have no LOS, who have missign saps score
recid = [int(j) for j in recid]
misak = (set(list(recidees)) - set(list(recid)))
misakidxs = [recidees.index(i) for i in misak]
invalididxs = [recidees.index(i) for i in invalids]
allmiss = misakidxs + invalididxs
allmiss = sorted(allmiss)
newsaps = []
newapache = []
newmpm =[]
newsofa = []
# coordinating the dictionaries obtained before removing invalid patients
for ind in range(len(allmiss)-1):
for icuind in range(1,5):
if allmiss[ind] in paticutypedictindex[icuind]:
paticutypedictindex[icuind].remove(allmiss[ind])
if allmiss[ind+1] in paticutypedictindex[icuind]:
paticutypedictindex[icuind].remove(allmiss[ind+1])
for val in paticutypedictindex[icuind]:
if val in range(allmiss[ind] +1,allmiss[ind+1]):
paticutypedictindex[icuind][(paticutypedictindex[icuind]).index(val)] = val - (ind+1)
for icuind in range(1,5):
for val in paticutypedictindex[icuind]:
if val > allmiss[-1]:
paticutypedictindex[icuind][(paticutypedictindex[icuind]).index(val)] = val - (len(allmiss))
realwholefeat = np.empty((3937,35))
reallos = [los[i] for i in range(len(los)) if losrecids[i] not in misak and losrecids[i] not in invalids ]
realages = []
realgenders = []
j = 0
l = 0
# fixing age and genders given the omitted patients
for k in recidees:
if k not in misak and k not in invalids :
realwholefeat[j,:] = wholefeat[l,:]
j +=1
realages.append(ages[l])
realgenders.append(genders[l])
l +=1
j = 0
l = 0
for k in recid:
if k not in invalids :
newsaps.append(float(saps[l]))
newapache.append(float(apache[l]))
newmpm.append(float(mpm[l]))
newsofa.append(float(sofa[l]))
l +=1
wholefeat = realwholefeat
los = reallos
ages = realages
genders = realgenders
allpats = 0
maxpat = 0
for i in range(1,5):
allpats += len(paticutypedictindex[i])
maxpat = max(max(paticutypedictindex[i]),maxpat)
# fixing dictionary values for the removed patients
heartratedict = removeinvalidptsfromdict(heartratedict,allmiss)
WBCdict = removeinvalidptsfromdict(WBCdict,allmiss)
tempdict = removeinvalidptsfromdict(tempdict,allmiss)
GCSdict = removeinvalidptsfromdict(GCSdict,allmiss)
glucosedict = removeinvalidptsfromdict(glucosedict,allmiss)
NIDSdict = removeinvalidptsfromdict(NIDSdict,allmiss)
urinedict = removeinvalidptsfromdict(urinedict,allmiss)
# settting all values to the new ones
saps = newsaps
apache = newapache
mpm = newmpm
sofa = newsofa
outputfeats = np.column_stack((saps,apache,mpm,sofa))
# list of the dicts that you want to include in the model
listofalldicts = [heartratedict,WBCdict,tempdict,GCSdict,glucosedict,NIDSdict,urinedict]
nstates = range(2,9)
overlapflag = False
ordscores = [0] * len(nstates)
ovlapscores = [0] * len(nstates)
ordAvgVarPatches = [0] * len(nstates)
ordVarRadiiPatchesmean = [0] * len(nstates)
ordVarRadiiPatchesmedian = [0] * len(nstates)
ovlapAvgVarPatches = [0] * len(nstates)
ovlapVarRadiiPatchesmean = [0] * len(nstates)
ovlapVarRadiiPatchesmedian = [0] * len(nstates)
overcases = [True]
logcases = [False]
icutypes = [int(sys.argv[1])]
numofstatescases = [8]
resolutions = [8.0]
dictcases = {}
models = ["firstlastprobs"]
# name of the file to save the performance metrics in.
realtitle = "sapspaperreal5" + ".csv"
w = csv.writer(open(realtitle, "a"))
w.writerow(["model " , "abbrevName","Overlapping " , "Log scale for LOS","Number of States","Time Resolution ", "ICUType " , "HMM RMSE ","Baseline RMSE","sapsRMSE ","alloutRMSE ""Win1","win2","win3"])
for numofstates in numofstatescases:
for over in overcases:
for log in logcases:
for model in models:
for resolution in resolutions:
for icutype in icutypes:
name = ""
if over:
name += "over"
else :
name += "nonoverlapping"
if log :
name += "logLOS"
else :
name += "normalLOS"
name += "numofstates="
name += str(numofstates)
name += "icutype="
listofalldicts = [heartratedict,WBCdict,tempdict,GCSdict,glucosedict,NIDSdict,urinedict]
resolutions = [resolution] * 7
(validpatientsindices,realfeatmtrxtrain1,realfeatmtrxtest1,KNNfeats,reallos1,inputHmmallVars,ovlapinputHmmallVars,trainindices,testindices) = generatetraintestsplit(listofalldicts,wholefeat,los,icutype,ages,genders,urinedict,paticutypedictindex,resolutions)
dictindices= range(7)
(ordscores[0],ordselalg,ordselcovartype,ovlapscores[0],ovlapselalg,ovlapselcovartype ,traininghmmfeats1,testhmmfeats1,ytrain1,ytest1,ordAvgVarPatches[0],ordVarRadiiPatchesmean[0],ordVarRadiiPatchesmedian[0],ovlapAvgVarPatches[0],ovlapVarRadiiPatchesmean[0],ovlapVarRadiiPatchesmedian[0],ordtransmat, ovlaptransmat , ordpii , ovlappii ) = learnhmm (validpatientsindices,KNNfeats,reallos1,inputHmmallVars,ovlapinputHmmallVars,trainindices,testindices,dictindices,resolution,numofstates,icutype,over,model)
sapstrain = [saps[lam] for lam in trainindices]
sapstest = [saps[lamb] for lamb in testindices]
sapstrain = np.array(sapstrain)
sapstest = np.array(sapstest)
outputfeatstrain = outputfeats[trainindices,:]
outputfeatstest = outputfeats[testindices,:]
# setting hmm flag to true and running the linear regression
hmm = True
hmmmsescore = Linearregr(traininghmmfeats1, testhmmfeats1, ytrain1, ytest1,hmm,log,numofstates,resolution,icutype,model)
hmm = False
balgmse = performbaseline(realfeatmtrxtrain1,ytrain1,realfeatmtrxtest1,ytest1)
baselinescore = Linearregr(realfeatmtrxtrain1, realfeatmtrxtest1, ytrain1, ytest1,hmm,log,numofstates,resolution,icutype,model)
hmm = True
sapsscore = Linearregr(sapstrain.reshape(-1, 1), sapstest.reshape(-1, 1), ytrain1, ytest1,hmm,log,numofstates,resolution,icutype,model)
success1 = int(hmmmsescore < baselinescore)
success2 = int(balgmse< baselinescore)
success3 = int(hmmmsescore< sapsscore)
print "hmm"
print hmmmsescore
print "baseline"
print baselinescore
print "saps"
print sapsscore
# writes the statistics for this run to the file for later inspection
w.writerow([model,name ,over,log, numofstates,resolution,icutype,hmmmsescore ,baselinescore,balgmse,sapsscore,success1,success2,success3])
def heatmapofvitalschange(ovlaplosidx,nstates,ovlapinputtest):
'''
plots heatmap of changes across time for different features and different start end pairs
'''
clusters = ovlaplosidx.keys()
for cluster in clusters:
if len(ovlaplosidx[cluster]) > 0:
mtrx = []
for i in range(7):
row = np.mean(ovlapinputtest[ovlaplosidx[cluster],:,i],axis = 0)
mtrx.append(row)
plt.close()
mtrx = scipy.stats.zscore(mtrx,axis = 1)
ax = sns.heatmap(mtrx,yticklabels = [ "HR " ,"WBC " , "Temp ", "GCS ","Glucose ", "NIDBP ","Urine "],cmap="Greens")
plt.xlabel("Time point Index")
realtitle = "vitalsheatmap" + "cluster " + str(cluster) + str(nstates) + ".png"
(plt.savefig(realtitle))
def sortdiagonal(mtrx):
diagonal = np.diag(mtrx)
idx = np.argsort(diagonal)
sorted = mtrx[idx,:][:,idx]
return sorted
def stabilityrep(resolution,icutype,wholefeat,los,ages,genders,urinedict,paticutypedictindex,listofalldicts,numofstates,over,model,nruns):
'''
Shows how much stable the model is given different initialization
'''
ordtransmats = np.empty((nruns,numofstates,numofstates))
ordpiis = np.empty((nruns,numofstates))
ovlaptransmats = np.empty((nruns,numofstates,numofstates))
ovlappiis = np.empty((nruns,numofstates))
avgordtransmat = np.empty((numofstates,numofstates))
avgovlaptransmat = np.empty((numofstates,numofstates))
avgordpii = np.empty((1,numofstates))
avgovlappii = np.empty((1,numofstates))
nelemsmtrx = numofstates * numofstates
for i in range(nruns):
resolutions = [resolution] * 7
(validpatientsindices,realfeatmtrxtrain1,realfeatmtrxtest1,KNNfeats,reallos1,inputHmmallVars,ovlapinputHmmallVars,trainindices,testindices) = generatetraintestsplit(listofalldicts,wholefeat,los,icutype,ages,genders,urinedict,paticutypedictindex,resolutions)
dictindices= range(7)
(ordscores,ordselalg,ordselcovartype,ovlapscores,ovlapselalg,ovlapselcovartype ,traininghmmfeats1,testhmmfeats1,ytrain1,ytest1,ordAvgVarPatches,ordVarRadiiPatchesmean,ordVarRadiiPatchesmedian,ovlapAvgVarPatches, \
ovlapVarRadiiPatchesmean,ovlapVarRadiiPatchesmedian ,ordtransmat, ovlaptransmat , ordpii , ovlappii ) = \
learnhmm (validpatientsindices,KNNfeats,reallos1,inputHmmallVars,ovlapinputHmmallVars,trainindices,testindices,dictindices,resolution,numofstates,icutype,over,model)
ordtransmats[i,:,:] = sortdiagonal(ordtransmat)
ovlaptransmats[i,:,:] = sortdiagonal(ovlaptransmat)
ordpiis[i,:] = sortdiagonal(ordpii)
ovlappiis[i,:] = sortdiagonal(ovlappii)
for i in range(numofstates):
avgordpii = np.mean(ordpiis[:,i])
avgovlappii = np.mean(ovlappiis[:,i])
for j in range(numofstates):
avgordtransmat[i,j] = np.mean(ordtransmats[:,i,j])
avgovlaptransmat[i,j] = np.mean(ovlaptransmats[:,i,j])
diffordtransmat = np.empty((numofstates,numofstates))
diffovlaptransmat = np.empty((numofstates,numofstates))
diffordpii = np.empty((1,numofstates))
diffovlappii = np.empty((1,numofstates))
for i in range(nruns):
diffordtransmat += np.absolute(ordtransmats[i,:,:] - avgordtransmat )
diffovlaptransmat += np.absolute(ovlaptransmats[i,:,:] - avgovlaptransmat )
diffordpii += np.absolute(ordpiis[i,:] - avgordpii )
diffovlappii += np.absolute(ovlappiis[i,:] - avgovlappii )
varavgordpii = float(np.sum(diffordpii)) / float(numofstates * nruns)
varavgovlappii = float(np.sum(diffovlappii)) / float(numofstates * nruns)
varavgordtransmat = float(np.sum(diffordtransmat)) / float(nelemsmtrx * nruns)
varavgovlaptransmat = float(np.sum(diffovlaptransmat)) / float(nelemsmtrx * nruns)
return (varavgordpii,varavgordpii,varavgordtransmat,varavgordtransmat)
def generatetraintestsplit(listofalldicts,featmtrx,los,icutype,ages,genders,urinedict,paticutypedictindex,resolutions):
'''
Given the ICU type generates the los and feature matrices of train and test plus indices associated with test and train
Input: aggregate feature matrix, ages, genders, dictionary with key as ICU type and value showing indexes showing the patients
who belong to that ICU type
Output: test and train indices, length of stays, feature for KNN clustering, input for non overlapping and overlapping cases of HMM modeling
'''
numvars = 7
inputHmmallVars = [0] * numvars
ovlapinputHmmallVars = [0] * numvars
validpatientsindicesallVars = [[] for i in range(numvars)]
urineflag = False
if icutype < 5:
npatients = len(paticutypedictindex[icutype])
numfeats = np.shape(featmtrx)[1]
ages = [int(age) for age in ages]
ages = [ages[paticutypedictindex[icutype][i]] for i in range(len(paticutypedictindex[icutype]))]
genders = [genders[paticutypedictindex[icutype][i]] for i in range(len(paticutypedictindex[icutype]))]
# generating input of hmm for each dictionary separately
for i in range(numvars):
if listofalldicts[i] == urinedict:
urineflag= True
(ovlapinputHmmallVars[i],inputHmmallVars[i],validpatientsindicesallVars[i]) = generateinputoutputbasedondict(npatients, resolutions[i], listofalldicts[i], paticutypedictindex, icutype,urineflag)
validpatientsindices = validpatientsindicesallVars[0]
# Intersecting to get the patients who were valid across all dictionaries
for i in range(1,numvars):
validpatientsindices = list(set(validpatientsindices).intersection(set(validpatientsindicesallVars[i])))
realfeatmtrx = np.empty((len(validpatientsindices),numfeats))
reallos = [0] * len(validpatientsindices)
KNNfeats = np.column_stack((ages,genders))
for i in range(len(validpatientsindices)):
realfeatmtrx[i,:] = featmtrx[paticutypedictindex[icutype][validpatientsindices[i]],:]
reallos[i] = los[paticutypedictindex[icutype][validpatientsindices[i]]]
# aggregating age, gender and feature matrices for combination of icu types
elif icutype > 7:
numfeats = np.shape(featmtrx)[1]
if icutype == 8:
npatients = len(paticutypedictindex[1]) + len(paticutypedictindex[2])
ages1 = [ages[paticutypedictindex[1][i]] for i in range(len(paticutypedictindex[1]))]
genders1 = [genders[paticutypedictindex[1][i]] for i in range(len(paticutypedictindex[1]))]
ages2 = [ages[paticutypedictindex[2][i]] for i in range(len(paticutypedictindex[2]))]
genders2 = [genders[paticutypedictindex[2][i]] for i in range(len(paticutypedictindex[2]))]
ages = ages1 + ages2
genders = genders1 + genders2
realpaticutypedictindex = paticutypedictindex[1] + paticutypedictindex[2]
if icutype == 12:
npatients = len(paticutypedictindex[3]) + len(paticutypedictindex[4])
ages1 = [ages[paticutypedictindex[3][i]] for i in range(len(paticutypedictindex[3]))]
genders1 = [genders[paticutypedictindex[3][i]] for i in range(len(paticutypedictindex[3]))]
ages2 = [ages[paticutypedictindex[4][i]] for i in range(len(paticutypedictindex[4]))]
genders2 = [genders[paticutypedictindex[4][i]] for i in range(len(paticutypedictindex[4]))]
ages = ages1 + ages2
genders = genders1 + genders2
realpaticutypedictindex = paticutypedictindex[3] + paticutypedictindex[4]
if icutype == 10:
npatients = len(paticutypedictindex[2]) + len(paticutypedictindex[3])
ages1 = [ages[paticutypedictindex[2][i]] for i in range(len(paticutypedictindex[2]))]
genders1 = [genders[paticutypedictindex[2][i]] for i in range(len(paticutypedictindex[2]))]
ages2 = [ages[paticutypedictindex[3][i]] for i in range(len(paticutypedictindex[3]))]
genders2 = [genders[paticutypedictindex[3][i]] for i in range(len(paticutypedictindex[3]))]
ages = ages1 + ages2
genders = genders1 + genders2
realpaticutypedictindex = paticutypedictindex[2] + paticutypedictindex[3]
if icutype == 11:
npatients = len(paticutypedictindex[2]) + len(paticutypedictindex[4])
ages1 = [ages[paticutypedictindex[2][i]] for i in range(len(paticutypedictindex[2]))]
genders1 = [genders[paticutypedictindex[2][i]] for i in range(len(paticutypedictindex[2]))]
ages2 = [ages[paticutypedictindex[4][i]] for i in range(len(paticutypedictindex[4]))]
genders2 = [genders[paticutypedictindex[4][i]] for i in range(len(paticutypedictindex[4]))]
ages = ages1 + ages2
genders = genders1 + genders2
realpaticutypedictindex = paticutypedictindex[2] + paticutypedictindex[4]
if icutype == 13 :
npatients = len(paticutypedictindex[1]) + len(paticutypedictindex[2]) + len(paticutypedictindex[3])
ages1 = [ages[paticutypedictindex[1][i]] for i in range(len(paticutypedictindex[1]))]
genders1 = [genders[paticutypedictindex[1][i]] for i in range(len(paticutypedictindex[1]))]
ages2 = [ages[paticutypedictindex[2][i]] for i in range(len(paticutypedictindex[2]))]
genders2 = [genders[paticutypedictindex[2][i]] for i in range(len(paticutypedictindex[2]))]
ages3 = [ages[paticutypedictindex[3][i]] for i in range(len(paticutypedictindex[3]))]
genders3 = [genders[paticutypedictindex[3][i]] for i in range(len(paticutypedictindex[3]))]
ages = ages1 + ages2 + ages3
genders = genders1 + genders2 + ages3
realpaticutypedictindex = paticutypedictindex[1] + paticutypedictindex[2] + paticutypedictindex[3]
for i in range(numvars):
if listofalldicts[i] == urinedict:
urineflag= True
(ovlapinputHmmallVars[i],inputHmmallVars[i],validpatientsindicesallVars[i]) = generateinputoutputbasedondict(npatients, resolutions[i], listofalldicts[i], paticutypedictindex, icutype,urineflag)
validpatientsindices = validpatientsindicesallVars[0]
for i in range(1,numvars):
validpatientsindices = list(set(validpatientsindices).intersection(set(validpatientsindicesallVars[i])))
realfeatmtrx = np.empty((len(validpatientsindices),numfeats))
reallos = [0] * len(validpatientsindices)
KNNfeats = np.column_stack((ages,genders))
for i in range(len(validpatientsindices)):
realfeatmtrx[i,:] = featmtrx[realpaticutypedictindex[validpatientsindices[i]],:]
reallos[i] = los[realpaticutypedictindex[validpatientsindices[i]]]
else:
# all patients together
npatients = np.shape(featmtrx)[0]
numfeats = np.shape(featmtrx)[1]
ages = [int(age) for age in ages]
for i in range(numvars):
if listofalldicts[i] == urinedict:
urineflag= True
(ovlapinputHmmallVars[i],inputHmmallVars[i],validpatientsindicesallVars[i]) = generateinputoutputbasedondict(npatients, resolutions[i], listofalldicts[i], paticutypedictindex, icutype,urineflag)
validpatientsindices = validpatientsindicesallVars[0]
for i in range(1,numvars):
validpatientsindices = list(set(validpatientsindices).intersection(set(validpatientsindicesallVars[i])))
realfeatmtrx = np.empty((len(validpatientsindices),numfeats))
reallos = [0] * len(validpatientsindices)
KNNfeats = np.column_stack((ages,genders))
for i in range(len(validpatientsindices)):
if icutype < 5:
realfeatmtrx[i,:] = featmtrx[paticutypedictindex[icutype][validpatientsindices[i]],:]
reallos[i] = los[paticutypedictindex[icutype][validpatientsindices[i]]]
else:
realfeatmtrx[i,:] = featmtrx[[i],:]
reallos[i] = los[validpatientsindices[i]]
(testindices,trainindices) = stratifyBOlos(realfeatmtrx,reallos)
realfeatmtrxtrain = realfeatmtrx[trainindices,:]
realfeatmtrxtest = realfeatmtrx[testindices,:]
return (validpatientsindices,realfeatmtrxtrain,realfeatmtrxtest,KNNfeats,reallos,inputHmmallVars,ovlapinputHmmallVars,trainindices,testindices)
def reportfrequencyofchange(states):
'''
Shows the frequency of change for various features
'''
npatients = np.shape(states)[0]
ntimepoints = np.shape(states)[1]
changecounts = [0] * npatients
for i in range(npatients):
for j in range(1,ntimepoints):
if states[i,j] != states[i,j-1]:
changecounts[i] += 1
avgchangecounts = np.mean(np.array(changecounts))
measureOfChange = float(avgchangecounts) / float (ntimepoints-1)
return measureOfChange
def plotforoptimumpoints(everyxhours,nstates,ordAvgVarPatches,ordVarRadiiPatchesmean,ordVarRadiiPatchesmedian,ovlapAvgVarPatches,ovlapVarRadiiPatchesmean,ovlapVarRadiiPatchesmedian,ordscores,ovlapscores):
'''
Runs a grid search on time resolution and number of states and plots the result to assist with the best choice of paramerters
'''
plt.close()
plt.plot(nstates,ordscores)
plt.xlabel("Number of states")
plt.ylabel("LogLikelihood Value")
title1 = "nstateslikelihoodord" + str(everyxhours) + str(nstates[-1]) + ".png"
plt.savefig(title1)
plt.close()
plt.plot(nstates,ovlapscores)
title2 = "nstateslikelihoodoverlap" + str(everyxhours) + str(nstates[-1]) + ".png"
plt.xlabel("Number of states")
plt.ylabel("LogLikelihood Value")
plt.savefig(title2)
plt.close()
plt.plot(nstates,ordAvgVarPatches)
plt.xlabel("Number of states")
plt.ylabel("Average Variance of LOS within each Patch nonoverlapping")
title1 = "nstatesAvgVarord" + str(everyxhours) + str(nstates[-1]) + ".png"
plt.savefig(title1)
plt.close()
plt.plot(nstates,ovlapAvgVarPatches)
title2 = "nstatesAvgVarovlap" + str(everyxhours) + str(nstates[-1]) + ".png"
plt.xlabel("Number of states")
plt.ylabel("Average Variance of LOS within each Patch overlapping")
plt.savefig(title2)
plt.close()
plt.plot(nstates,ordVarRadiiPatchesmean)
plt.xlabel("Number of states")
plt.ylabel("Variance of Mean of LOS across Patches nonoverlapping")
title1 = "nstatesVarMeanord" + str(everyxhours) + str(nstates[-1]) + ".png"
plt.savefig(title1)
plt.close()
plt.plot(nstates,ovlapVarRadiiPatchesmean)
title2 = "nstatesVarMeanovlap" + str(everyxhours) + str(nstates[-1]) + ".png"
plt.xlabel("Number of states")
plt.ylabel("Variance of Mean of LOS across Patches overlapping")
plt.savefig(title2)
plt.close()
plt.plot(nstates,ordVarRadiiPatchesmedian)
plt.xlabel("Number of states")
plt.ylabel("Variance of median of LOS across Patches nonoverlapping")
title1 = "nstatesVarMedianord" + str(everyxhours) + str(nstates[-1]) + ".png"
plt.savefig(title1)
plt.close()
plt.plot(nstates,ovlapVarRadiiPatchesmedian)
title2 = "nstatesVarMedianovlap" + str(everyxhours) + str(nstates[-1]) + ".png"
plt.xlabel("Number of states")
plt.ylabel("Variance of Median of LOS across Patches overlapping")
plt.savefig(title2)
plt.close()
def generateinputoutputbasedondict(npatients,everyxhours,featdict,paticutypedictindex,icutype,urineflag):
'''
Generates feature specific dictionary for a given type
Input : overall number of patients, time resolution, the particular feature dictionary, patient ICU type dictionary, ICUtype, urine flag
Output: Overlapping hmm input , non overlapping hmm input and valid patients who have at least one measure for that feature across timepoints
'''
dimensionality = int(math.floor(48.0/float(everyxhours)))
overdimensionality = (2 * dimensionality) -1
inputhmm=np.zeros((npatients,dimensionality))
ovlapinputhmm=np.zeros((npatients,overdimensionality))
counts = (np.ones((npatients,dimensionality)))
ovcounts = (np.ones((npatients,overdimensionality)))
voidindices = []
lastovlaptimepoint = 48 - everyxhours
# aggregating for time points
if icutype < 5:
for j in range(npatients):
if len(featdict[paticutypedictindex[icutype][j]][0]) != 0 :
ovlapinputhmmlistval = [[] for i in range(overdimensionality)]
ovlapinputhmmtime = [[] for i in range(overdimensionality)]
inputhmmtime = [[] for i in range(dimensionality)]
inputhmmlistval = [[] for i in range(dimensionality)]
for (time,value )in featdict[paticutypedictindex[icutype][j]][0]:
indice = int(math.floor((time-1) / (everyxhours*60)))
if not (time < (everyxhours) * 60 or time > lastovlaptimepoint * 60 ):
ovindice = 2 * (int(math.floor((time + (everyxhours * 60) -1)/ (everyxhours * 60)))) - 1
ovlapinputhmmtime[ovindice].append(value)
ovlapinputhmmlistval[ovindice].append(value)
inputhmmtime[indice].append(value)
inputhmmlistval[indice].append(value)
ovlapinputhmmtime[2 * indice].append(value)
ovlapinputhmmlistval[2 * indice].append(value)
for i in range(dimensionality):
if len(inputhmmtime[i]) > 0:
maxind = inputhmmtime[i].index(max(inputhmmtime[i]))
inputhmm[j,i] = inputhmmlistval[i][maxind]
for i in range(overdimensionality):
if len(ovlapinputhmmtime[i]) > 0:
maxind = ovlapinputhmmtime[i].index(max(ovlapinputhmmtime[i]))
ovlapinputhmm[j,i] = ovlapinputhmmlistval[i][maxind]
else:
voidindices.append(j)
allzeros1 = list(set(list(np.where(~inputhmm.any(axis = 1))[0])))
allzeros2 = list(set(list(np.where(~ovlapinputhmm.any(axis = 1))[0])))
allzeros = []
allzeros += allzeros1
allzeros += allzeros2
validpatientsindices = list(set(range(npatients)) - set(allzeros))
elif icutype > 7:
if icutype == 8:
# type 1 and 2
for j in range(npatients):
if j >= len(paticutypedictindex[1]):
icupatientidx = paticutypedictindex[2]
k= j-len(paticutypedictindex[1])
else:
icupatientidx = paticutypedictindex[1]
k= j
if len(featdict[icupatientidx[k]][0]) != 0 :
ovlapinputhmmlistval = [[] for i in range(overdimensionality)]
ovlapinputhmmtime = [[] for i in range(overdimensionality)]
inputhmmtime = [[] for i in range(dimensionality)]
inputhmmlistval = [[] for i in range(dimensionality)]
for (time,value )in featdict[icupatientidx[k]][0]:
indice = int(math.floor((time-1) / (everyxhours*60)))
if not (time < (everyxhours) * 60 or time > lastovlaptimepoint * 60 ):
ovindice = 2 * (int(math.floor((time + (everyxhours * 60) -1)/ (everyxhours * 60)))) - 1
ovlapinputhmmtime[ovindice].append(value)
ovlapinputhmmlistval[ovindice].append(value)
inputhmmtime[indice].append(value)
inputhmmlistval[indice].append(value)
ovlapinputhmmtime[2 * indice].append(value)
ovlapinputhmmlistval[2 * indice].append(value)
for i in range(dimensionality):
if len(inputhmmtime[i]) > 0:
maxind = inputhmmtime[i].index(max(inputhmmtime[i]))
inputhmm[j,i] = inputhmmlistval[i][maxind]
for i in range(overdimensionality):
if len(ovlapinputhmmtime[i]) > 0:
maxind = ovlapinputhmmtime[i].index(max(ovlapinputhmmtime[i]))
ovlapinputhmm[j,i] = ovlapinputhmmlistval[i][maxind]
else:
voidindices.append(j)
allzeros1 = list(set(list(np.where(~inputhmm.any(axis = 1))[0])))
allzeros2 = list(set(list(np.where(~ovlapinputhmm.any(axis = 1))[0])))
allzeros = []
allzeros += allzeros1
allzeros += allzeros2
validpatientsindices = list(set(range(npatients)) - set(allzeros))
if icutype == 12:
# type 3,4
for j in range(npatients):
if j >= len(paticutypedictindex[3]):
icupatientidx = paticutypedictindex[4]
k= j-len(paticutypedictindex[3])
else:
icupatientidx = paticutypedictindex[3]
k= j
if len(featdict[icupatientidx[k]][0]) != 0 :
ovlapinputhmmlistval = [[] for i in range(overdimensionality)]
ovlapinputhmmtime = [[] for i in range(overdimensionality)]
inputhmmtime = [[] for i in range(dimensionality)]
inputhmmlistval = [[] for i in range(dimensionality)]
for (time,value )in featdict[icupatientidx[k]][0]:
indice = int(math.floor((time-1) / (everyxhours*60)))
if not (time < (everyxhours) * 60 or time > lastovlaptimepoint * 60 ):
ovindice = 2 * (int(math.floor((time + (everyxhours * 60) -1)/ (everyxhours * 60)))) - 1
ovlapinputhmmtime[ovindice].append(value)
ovlapinputhmmlistval[ovindice].append(value)
inputhmmtime[indice].append(value)
inputhmmlistval[indice].append(value)
ovlapinputhmmtime[2 * indice].append(value)
ovlapinputhmmlistval[2 * indice].append(value)
for i in range(dimensionality):
if len(inputhmmtime[i]) > 0:
maxind = inputhmmtime[i].index(max(inputhmmtime[i]))
inputhmm[j,i] = inputhmmlistval[i][maxind]
for i in range(overdimensionality):
if len(ovlapinputhmmtime[i]) > 0:
maxind = ovlapinputhmmtime[i].index(max(ovlapinputhmmtime[i]))
ovlapinputhmm[j,i] = ovlapinputhmmlistval[i][maxind]
else:
voidindices.append(j)
allzeros1 = list(set(list(np.where(~inputhmm.any(axis = 1))[0])))
allzeros2 = list(set(list(np.where(~ovlapinputhmm.any(axis = 1))[0])))
allzeros = []
allzeros += allzeros1
allzeros += allzeros2
validpatientsindices = list(set(range(npatients)) - set(allzeros))
if icutype == 10:
# type 2,3
for j in range(npatients):
if j >= len(paticutypedictindex[2]):
icupatientidx = paticutypedictindex[3]
k= j-len(paticutypedictindex[2])
else:
icupatientidx = paticutypedictindex[2]
k= j
if len(featdict[icupatientidx[k]][0]) != 0 :
ovlapinputhmmlistval = [[] for i in range(overdimensionality)]
ovlapinputhmmtime = [[] for i in range(overdimensionality)]
inputhmmtime = [[] for i in range(dimensionality)]
inputhmmlistval = [[] for i in range(dimensionality)]
for (time,value )in featdict[icupatientidx[k]][0]:
indice = int(math.floor((time-1) / (everyxhours*60)))
if not (time < (everyxhours) * 60 or time > lastovlaptimepoint * 60 ):
ovindice = 2 * (int(math.floor((time + (everyxhours * 60) -1)/ (everyxhours * 60)))) - 1
ovlapinputhmmtime[ovindice].append(value)
ovlapinputhmmlistval[ovindice].append(value)
inputhmmtime[indice].append(value)
inputhmmlistval[indice].append(value)
ovlapinputhmmtime[2 * indice].append(value)
ovlapinputhmmlistval[2 * indice].append(value)
for i in range(dimensionality):
if len(inputhmmtime[i]) > 0:
maxind = inputhmmtime[i].index(max(inputhmmtime[i]))
inputhmm[j,i] = inputhmmlistval[i][maxind]
for i in range(overdimensionality):
if len(ovlapinputhmmtime[i]) > 0:
maxind = ovlapinputhmmtime[i].index(max(ovlapinputhmmtime[i]))
ovlapinputhmm[j,i] = ovlapinputhmmlistval[i][maxind]
else:
voidindices.append(j)
if ~(urineflag):
for i in range(npatients):
for j in range(dimensionality):
inputhmm[i,j] = np.array([(float(float(inputhmm[i,j]) / float(counts[i,j])))])
for k in range(overdimensionality):
ovlapinputhmm[i,k] = np.array([(float(float(ovlapinputhmm[i,k]) / float(ovcounts[i,k])))])
allzeros1 = list(set(list(np.where(~inputhmm.any(axis = 1))[0])))
allzeros2 = list(set(list(np.where(~ovlapinputhmm.any(axis = 1))[0])))
allzeros = []
allzeros += allzeros1
allzeros += allzeros2
validpatientsindices = list(set(range(npatients)) - set(allzeros))
if icutype == 11:
# type 2 and 4
for j in range(npatients):
if j >= len(paticutypedictindex[2]):
icupatientidx = paticutypedictindex[4]
k= j-len(paticutypedictindex[2])
else:
icupatientidx = paticutypedictindex[2]
k = j
if len(featdict[icupatientidx[k]][0]) != 0 :
ovlapinputhmmlistval = [[] for i in range(overdimensionality)]
ovlapinputhmmtime = [[] for i in range(overdimensionality)]
inputhmmtime = [[] for i in range(dimensionality)]
inputhmmlistval = [[] for i in range(dimensionality)]
for (time,value )in featdict[icupatientidx[k]][0]:
indice = int(math.floor((time-1) / (everyxhours*60)))
if not (time < (everyxhours) * 60 or time > lastovlaptimepoint * 60 ):
ovindice = 2 * (int(math.floor((time + (everyxhours * 60) -1)/ (everyxhours * 60)))) - 1
ovlapinputhmmtime[ovindice].append(value)
ovlapinputhmmlistval[ovindice].append(value)
inputhmmtime[indice].append(value)
inputhmmlistval[indice].append(value)
ovlapinputhmmtime[2 * indice].append(value)
ovlapinputhmmlistval[2 * indice].append(value)
for i in range(dimensionality):
if len(inputhmmtime[i]) > 0:
maxind = inputhmmtime[i].index(max(inputhmmtime[i]))
inputhmm[j,i] = inputhmmlistval[i][maxind]
for i in range(overdimensionality):
if len(ovlapinputhmmtime[i]) > 0:
maxind = ovlapinputhmmtime[i].index(max(ovlapinputhmmtime[i]))
ovlapinputhmm[j,i] = ovlapinputhmmlistval[i][maxind]
else:
voidindices.append(j)
if ~(urineflag):
for i in range(npatients):
for j in range(dimensionality):
inputhmm[i,j] = np.array([(float(float(inputhmm[i,j]) / float(counts[i,j])))])
for k in range(overdimensionality):
ovlapinputhmm[i,k] = np.array([(float(float(ovlapinputhmm[i,k]) / float(ovcounts[i,k])))])
allzeros1 = list(set(list(np.where(~inputhmm.any(axis = 1))[0])))
allzeros2 = list(set(list(np.where(~ovlapinputhmm.any(axis = 1))[0])))
allzeros = []
allzeros += allzeros1
allzeros += allzeros2
validpatientsindices = list(set(range(npatients)) - set(allzeros))
if icutype == 13:
# type 1 and 2 and 3
for j in range(npatients):
if j >= len(paticutypedictindex[2]) + len(paticutypedictindex[1]):
icupatientidx = paticutypedictindex[3]
k= j- (len(paticutypedictindex[2]) + len(paticutypedictindex[1]))
elif j >= len(paticutypedictindex[1]) :
icupatientidx = paticutypedictindex[2]
k= j - len(paticutypedictindex[1])
else:
icupatientidx = paticutypedictindex[1]
k= j
if len(featdict[icupatientidx[k]][0]) != 0 :
ovlapinputhmmlistval = [[] for i in range(overdimensionality)]
ovlapinputhmmtime = [[] for i in range(overdimensionality)]
inputhmmtime = [[] for i in range(dimensionality)]
inputhmmlistval = [[] for i in range(dimensionality)]
for (time,value )in featdict[icupatientidx[k]][0]:
indice = int(math.floor((time-1) / (everyxhours*60)))
if not (time < (everyxhours) * 60 or time > lastovlaptimepoint * 60 ):
ovindice = 2 * (int(math.floor((time + (everyxhours * 60) -1)/ (everyxhours * 60)))) - 1
ovlapinputhmmtime[ovindice].append(value)
ovlapinputhmmlistval[ovindice].append(value)
inputhmmtime[indice].append(value)
inputhmmlistval[indice].append(value)
ovlapinputhmmtime[2 * indice].append(value)
ovlapinputhmmlistval[2 * indice].append(value)
for i in range(dimensionality):
if len(inputhmmtime[i]) > 0:
maxind = inputhmmtime[i].index(max(inputhmmtime[i]))
inputhmm[j,i] = inputhmmlistval[i][maxind]
for i in range(overdimensionality):
if len(ovlapinputhmmtime[i]) > 0:
maxind = ovlapinputhmmtime[i].index(max(ovlapinputhmmtime[i]))
ovlapinputhmm[j,i] = ovlapinputhmmlistval[i][maxind]
else:
voidindices.append(j)
if ~(urineflag):
for i in range(npatients):
for j in range(dimensionality):
inputhmm[i,j] = np.array([(float(float(inputhmm[i,j]) / float(counts[i,j])))])
for k in range(overdimensionality):
ovlapinputhmm[i,k] = np.array([(float(float(ovlapinputhmm[i,k]) / float(ovcounts[i,k])))])
allzeros1 = list(set(list(np.where(~inputhmm.any(axis = 1))[0])))
allzeros2 = list(set(list(np.where(~ovlapinputhmm.any(axis = 1))[0])))
allzeros = []
allzeros += allzeros1
allzeros += allzeros2
validpatientsindices = list(set(range(npatients)) - set(allzeros))
else:
# meaning all patients
for j in range(npatients-1):
if j in featdict.keys():
if len(featdict[j]) != 0 :
for (time,value ) in featdict[j][0]:
indice = int(math.floor((time-1) / (everyxhours*60)))
if not (time < (everyxhours * 60) or time > lastovlaptimepoint * 60 ):
ovindice = 2 * (int(math.floor((time + (everyxhours * 60) - 1)/ (everyxhours * 60)))) - 1
ovlapinputhmm [j,ovindice] += value
ovcounts[j,ovindice] += 1
ovlapinputhmm[j,2 * indice] += value
inputhmm[j,indice] += value
counts[j,indice] +=1
ovcounts[j,2 * indice] +=1
else:
voidindices.append(j)
if ~(urineflag):
for i in range(npatients-1):
for j in range(dimensionality):
inputhmm[i,j] = np.array([(float(float(inputhmm[i,j]) / float(counts[i,j])))])
for k in range(overdimensionality):
ovlapinputhmm[i,k] = np.array([(float(float(ovlapinputhmm[i,k]) / float(ovcounts[i,k])))])
allzeros = list(set(list(np.where(~inputhmm.any(axis = 1))[0])))
validpatientsindices = list(set(range(npatients)) - set(allzeros))
return (ovlapinputhmm,inputhmm,validpatientsindices)
def find2mostcertaintimepointsidx(indiv_chosenstate_probs,ovlapindiv_chosenstate_probs):
'''
Finds the probabilites belonging to the most certain time points and uses them as features, this did not work :D
'''
numpatients = np.shape(indiv_chosenstate_probs)[0]
dimensionality = np.shape(indiv_chosenstate_probs)[1]
overdimensionality = np.shape(ovlapindiv_chosenstate_probs)[1]
ordfirstmaxstateidx = [0] * (numpatients)
ordsecondmaxstateidx = [0] * (numpatients)
ovlapfirstmaxstateidx = [0] * (numpatients)
ovlapsecondmaxstateidx = [0] * (numpatients)
for i in range(numpatients):
indlist = list(indiv_chosenstate_probs[i,:])
ovlaplist = list(ovlapindiv_chosenstate_probs[i,:])
ordfirstmaxstateidx[i] = indlist.index(max(indlist))
ovlapfirstmaxstateidx[i] = ovlaplist.index(max(ovlaplist))
ordexceptmax = max([indlist[j] for j in range(dimensionality) if j !=ordfirstmaxstateidx[i]])
ovlapexceptmax = max([ovlaplist[j] for j in range(overdimensionality) if j !=ovlapfirstmaxstateidx[i]])
ordsecondmaxstateidx[i] = indlist.index(ordexceptmax)
ovlapsecondmaxstateidx[i] = ovlaplist.index(ovlapexceptmax)
return (ordfirstmaxstateidx,ordsecondmaxstateidx,ovlapfirstmaxstateidx,ovlapsecondmaxstateidx)
def applybestPCA(featmtrx):
maxim = np.shape(featmtrx)[1]
ncomponents = [2,maxim]
i = 0
explained = 0
while(i <len(ncomponents) and explained < 0.95):
pca = PCA(n_components=ncomponents[i])
pca.fit(featmtrx)
pcafeatmtrx = pca.fit_transform(featmtrx)
explained = (sum(pca.explained_variance_ratio_))
i += 1
plt.close()
ax = sns.heatmap(pca.components_)
plt.xlabel("selected component")
plt.ylabel("original feats")
realtitle = "PCAheatmap" + ".png"
(plt.savefig(realtitle))
return ncomponents[i-1]
def Linearregr(trainingx,testx,trainingy,testy,hmm,log,numofstate,everyxhours,icutype,model):
'''
runs the best linear regression model lasso on the probability features, or baselien feature, to predict length of stay
Input: probability train and test features, or baseline features and other model parameters
Output: MSE error and predicted LOS
'''
if hmm:
hmmtitile = "hmm"
else:
hmmtitile = ""
if log:
logtrainingy = logaritmizelos(trainingy)
logtesty = logaritmizelos(testy)
else :
logtrainingy = trainingy
logtesty = testy
# scaling both training and test using the same scaler
scaler = sklearn.preprocessing.StandardScaler().fit(trainingx)
trainingx = scaler.transform(trainingx)
testx = scaler.transform(testx)
featmtrx = np.concatenate((trainingx,testx),axis = 0)
totsamp = np.shape(featmtrx)[0]
numtrain = np.shape(trainingx)[0]
# applying pca based on the flag, only if the mode is not
if hmm:
pcafeatmtrx = featmtrx
else:
ncomp = applybestPCA(featmtrx)
pca = PCA(n_components=ncomp)
pca.fit(featmtrx)
pcafeatmtrx = pca.fit_transform(featmtrx)
sapsdetect = len(np.shape(pcafeatmtrx))
if sapsdetect != 1:
trainingfeats = pcafeatmtrx[0:numtrain,:]
testfeats = pcafeatmtrx[numtrain:,:]
else:
trainingfeats = pcafeatmtrx[0:numtrain]
testfeats = pcafeatmtrx[numtrain:]
trainingfeats = trainingfeats.reshape((numtrain,1))
testfeats = testfeats.reshape((totsamp-numtrain,1))
# running cross validation for linear regresssion
bestalpha = lrcrossvalidation(trainingfeats,logtrainingy,'Lasso')
testmodely = doLRandreport(trainingfeats, logtrainingy, testfeats, logtesty,bestalpha,'Lasso')
plottitle = hmmtitile + "Lasso" + "numofstate=" + str(numofstate) + "resolution" + str(everyxhours) + "icutype" + str(icutype) + model
plotscatter(logtesty, testmodely,plottitle,1)
errors = (testmodely - logtesty) ** 2
# shows the actual histogram
# histitle = "hist" + plottitle
testmse = np.sqrt(((float( np.sum( (testmodely - logtesty) ** 2 ))) / float(len(testmodely))))
mseerror = testmse
# plt.close()
# plt.hist(errors, bins=10 )
# filename = histitle + ".png"
# plt.savefig(filename)
# plt.close()
return mseerror
def startendlosvisualizerweighted(indivtrainstates,ovlapindivtrainstates,changestatindices,ovlapchangestatindices,nstates,ytrain,everyxhours,mean_chosenstate_prob_ord,mean_chosenstate_prob_ovlap,icutype):
dimensionality = np.shape(indivtrainstates)[1]
overdimensionality = np.shape(ovlapindivtrainstates)[1]
ordfirststates = indivtrainstates[:,0]
ovlapfirststates = ovlapindivtrainstates[:,0]
ordlaststates = indivtrainstates[:,dimensionality-1]
ovlaplaststates = ovlapindivtrainstates[:,overdimensionality-1]
allpossiblepair = [(i,j) for i in range(nstates) for j in range(nstates) ]
loschg =dict.fromkeys(allpossiblepair)
losnonchg = dict.fromkeys(allpossiblepair)
ordlos = dict.fromkeys(allpossiblepair)
ordlosidx = dict.fromkeys(allpossiblepair)
ovlaplosidx = dict.fromkeys(allpossiblepair)
ovlaploschg = dict.fromkeys(allpossiblepair)
ovlaplosnonchg = dict.fromkeys(allpossiblepair)
ovlaplos = dict.fromkeys(allpossiblepair)
listak = dict.fromkeys(allpossiblepair,0)
probchg =dict.fromkeys(allpossiblepair,0)
probnonchg = dict.fromkeys(allpossiblepair,0)
ordprob = dict.fromkeys(allpossiblepair,0)
ovlapprobchg = dict.fromkeys(allpossiblepair,0)
ovlapprobnonchg = dict.fromkeys(allpossiblepair,0)
ovlapprob = dict.fromkeys(allpossiblepair,0)
for key in allpossiblepair:
loschg[key] = list()
losnonchg[key] = list()
ordlos[key]= list()
ordlosidx[key] = list()
ovlaplosidx[key] = list()
ovlaploschg[key] = list()
ovlaplosnonchg[key]= list()
ovlaplos [key]= list()
for i in range(np.shape(indivtrainstates)[0]):
numbord = float((ytrain[i])) * float(mean_chosenstate_prob_ord[i])
numbovlap = float(ytrain[i]) *float( mean_chosenstate_prob_ovlap[i])
keyak = tuple((int(ordfirststates[i]),int(ordlaststates[i])))
keyakovlap = tuple((int(ovlapfirststates[i]),int(ovlaplaststates[i])))
ordprob[keyak] += float(mean_chosenstate_prob_ord[i])
(ordlos[keyak]).append(numbord)
(ordlosidx[keyak]).append(i)
(ovlaplosidx[keyak]).append(i)
listak[keyak] += 1
(ovlaplos[keyakovlap]).append(numbovlap)
ovlapprob [keyakovlap] += float( mean_chosenstate_prob_ovlap[i])
if i in changestatindices:
(loschg[keyak]).append(numbord)
probchg [keyak]+= float(mean_chosenstate_prob_ord[i])
else :
(losnonchg[keyak]).append(numbord)
probnonchg [keyak]+= float(mean_chosenstate_prob_ord[i])
if i in ovlapchangestatindices:
(ovlaploschg[keyakovlap]).append(numbovlap)
ovlapprobchg[keyakovlap] += float(mean_chosenstate_prob_ovlap[i])
else:
(ovlaplosnonchg[keyakovlap]).append(numbovlap)
ovlapprobnonchg[keyakovlap] += float(mean_chosenstate_prob_ovlap[i])
radiiordchg = dict.fromkeys(allpossiblepair,0)
radiiordnonchg = dict.fromkeys(allpossiblepair,0)
radiiovlapchg = dict.fromkeys(allpossiblepair,0)
radiiovlapnonchg = dict.fromkeys(allpossiblepair,0)
radiiord = dict.fromkeys(allpossiblepair,0)
radiioverlap = dict.fromkeys(allpossiblepair,0)
radiioverlapvariance = dict.fromkeys(allpossiblepair,0)
radiiordvariance = dict.fromkeys(allpossiblepair,0)
radiiordmedian = dict.fromkeys(allpossiblepair,0)
radiiovlapmedian = dict.fromkeys(allpossiblepair,0)
for i in range(nstates):
for j in range(nstates):
if len(ordlos[(i,j)]) >= 1:
radiiord[(i,j)] = float(float(np.sum(ordlos[(i,j)])) / float(ordprob[i,j]))
radiiordvariance[(i,j)] = np.var(ordlos[(i,j)])
radiiordmedian[(i,j)] = np.median(ordlos[(i,j)])
if len(loschg[(i,j)]) >= 1:
radiiordchg[(i,j)] = float(float(np.sum(loschg[(i,j)])) / float(probchg[i,j]))
if len(losnonchg[(i,j)]) >= 1:
radiiordnonchg[(i,j)] = float(float(np.sum(losnonchg[(i,j)])) / float(probnonchg[i,j]))
if len(ovlaplos[(i,j)]) >= 1:
radiioverlap[(i,j)] = float(float(np.sum(ovlaplos[(i,j)])) / float(ovlapprob[i,j]))
radiioverlapvariance[(i,j)] = np.var(ovlaplos[(i,j)])
radiiovlapmedian[(i,j)] = np.median(ovlaplos[(i,j)])
if len(ovlaploschg[(i,j)]) >= 1:
radiiovlapchg[(i,j)] = float(float(np.sum(ovlaploschg[(i,j)])) / float(ovlapprobchg[i,j]))
if len(ovlaplosnonchg[(i,j)]) >= 1:
radiiovlapnonchg[(i,j)] = float(float(np.sum(ovlaplosnonchg[(i,j)])) / float(ovlapprobnonchg[i,j]))
ordAvgVarPatches = np.mean(radiiordvariance.values())
ordVarRadiiPatchesmean = np.var(radiiord.values())
ordVarRadiiPatchesmedian = np.var(radiiordmedian.values())
ovlapAvgVarPatches = np.mean(radiioverlapvariance.values())
ovlapVarRadiiPatchesmean = np.var(radiioverlap.values())
ovlapVarRadiiPatchesmedian = np.var(radiiovlapmedian.values())
biggestloskeyord = keywithmaxval(radiiord)
biggestloskeyovlap = keywithmaxval(radiioverlap)
idxbiggestlosord = ordlosidx[biggestloskeyord]
idxbiggestlosovlap = ovlaplosidx[biggestloskeyovlap]
params = csv.writer(open("params.csv", "w"))
params.writerow([everyxhours,nstates,icutype])
dicttocsv(radiiord,ordlos,"ordweighted"+ str(icutype))
dicttocsv(radiiordchg,loschg,"ordchgweighted"+ str(icutype))
dicttocsv(radiiordnonchg,losnonchg,"ordnonchgweighted"+ str(icutype))
dicttocsv(radiioverlap,ovlaplos,"overlapweighted"+ str(icutype))
dicttocsv(radiiovlapchg,ovlaploschg,"overlapchgweighted"+ str(icutype))
dicttocsv(radiiovlapnonchg,ovlaplosnonchg,"overlapnonchgweighted"+ str(icutype))
return (idxbiggestlosord,idxbiggestlosovlap,ordAvgVarPatches,ordVarRadiiPatchesmean,ordVarRadiiPatchesmedian,ovlapAvgVarPatches,ovlapVarRadiiPatchesmean,ovlapVarRadiiPatchesmedian)
def plotlongestlosbasedoncertainty(idxbiggestlosord,idxbiggestlosovlap,ytrain,indiv_chosenstate_probs,ovlapindiv_chosenstate_probs,everyxhours,nstates,indivprobs,ovlapindivprobs,weighted,icutype):
'''
plots long staying patient for the purpose of comparing models with different number of states and time resoltions
'''
if weighted:
weight = "weighted"
else:
weight = ""
losord = [ytrain[i] for i in idxbiggestlosord]
losovlap = [ytrain[i] for i in idxbiggestlosovlap]
dimensionality = np.shape(indiv_chosenstate_probs)[1]
overdimensionality = np.shape(ovlapindiv_chosenstate_probs)[1]
realcertaintyord = np.empty((len(idxbiggestlosord),dimensionality,nstates))
realcertaintyovlap = np.empty((len(idxbiggestlosovlap),overdimensionality,nstates))