-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresults_analysis.py
1906 lines (1466 loc) · 101 KB
/
results_analysis.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
# Copyright (C) 2024 Antonio Rodriguez
#
# This file is part of Personalized-AI-Based-Do-It-Yourself-Glucose-Prediction-tool.
#
# Personalized-AI-Based-Do-It-Yourself-Glucose-Prediction-tool is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Personalized-AI-Based-Do-It-Yourself-Glucose-Prediction-tool is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Personalized-AI-Based-Do-It-Yourself-Glucose-Prediction-tool. If not, see <http://www.gnu.org/licenses/>.
# results_analysis.py
# This module contains different functions to analyze the results of the experiments
# after their full execution. Graphs included in our paper has been generated using
# these functions from a Jupyter Notebook.
# See functions documentation for more details.
from typing import Dict, List
import os
import json
import xlsxwriter
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import matplotlib.patches as mpatches
from matplotlib.lines import Line2D
def store_ind_results_in_Excel(exp_config : Dict, results_dir : str = r"C:\Users\aralmeida\Downloads\LibreViewRawData\1yr_npy_files"):
"""
Store the mean ± std. of the RMSE, MAE, MAPE, % ISO and % AB Parkes in an Excel file.
The same metrics are shown for each one of the 4-folds. Notice that these are evaluation
metrics, not training metrics.
This function assumes that there is a 'results_dictonary.json' file in each patient folder, and also
assumes that the directory is provided contains folders with the ID of each patients. If these assumptions
are not correct, the function will not work.
Each studied patient has its own sheet on his/her directory.
Each PH (Prediction Horizon) has its own Excel file. Inside each file, there is one sheet per
evaluated model.
Args:
exp_config (Dict): Dictionary with the experiment configuration wanted to be analyzed.
results_dir (str): Directory where the folders with each patient ID and the results_dictionary.json are placed.
Default: "C:\Users\aralmeida\Downloads\LibreViewRawData\1yr_npy_files"
Returns:
None
"""
# Go to the directory where all results are stored
os.chdir(results_dir)
# Iterate over the ID folders to generate the 4-folds
for id in os.listdir():
# Counter
i = 0
# Consider only folders, not .npy or .txt files
if ('npy' not in id) and ('txt' not in id) and ('svg' not in id) and ('png' not in id) and ('TEST' not in id) and ('h5' not in id) and ('xls' not in id) and ('evaluation' not in id) and ('pickle' not in id):
os.chdir(id)
# Open json file
with open('results_dictionary.json') as json_file:
results = json.load(json_file)
# Iterate over PH to generate different Excel files depending on the PH (not comparable between them)
for PH in exp_config['PH']:
# Filename
filename = 'results_' + str(PH) + 'min.xlsx'
# Index to access the dictionary results will vary because the greater PH, the greater the index
if PH == 30:
idx = 1
elif PH == 60:
idx = 3
# Create an Excel file
workbook = xlsxwriter.Workbook(filename)
# Create one sheet per model
for model in exp_config['model']:
# Add worksheet corresponding to the current model
worksheet = workbook.add_worksheet(model)
# Write the headers of the worksheet
worksheet.write(0, 0, 'Patient')
worksheet.write(0, 1, id)
worksheet.write(1, 0, 'PH')
worksheet.write(1, 1, PH)
worksheet.write(4, 1, 'Loss function')
worksheet.write(3, 2, 'RMSE')
worksheet.write(4, 2, 'MSE')
worksheet.write(4, 3, 'ISO')
worksheet.write(3, 4, 'MAE')
worksheet.write(4, 4, 'MSE')
worksheet.write(4, 5, 'ISO')
worksheet.write(3, 6, 'MAPE')
worksheet.write(4, 6, 'MSE')
worksheet.write(4, 7, 'ISO')
worksheet.write(3, 8, '% Parkes AB')
worksheet.write(4, 8, 'MSE')
worksheet.write(4, 9, 'ISO')
worksheet.write(3, 10, '% ISO')
worksheet.write(4, 10, 'MSE')
worksheet.write(4, 11, 'ISO')
worksheet.write(5, 1, '1-fold')
worksheet.write(6, 1, '2-fold')
worksheet.write(7, 1, '3-fold')
worksheet.write(8, 1, '4-fold')
worksheet.write(9, 1, 'mean ± std')
# Itreate over the loss functions and write the results
for loss in exp_config['loss_function']:
# Obtain key to access the correspondant result
key = 'multi_N{}_step1_PH{}_month-wise-4-folds_min-max_None_{}_{}'.format(exp_config['N'][0], PH, model, loss)
if loss == 'root_mean_squared_error':
# RMSE
worksheet.write(5, 2, results[key][model]['1-fold']["normal "]["RMSE"][idx]) # typo: space after normal to be corrected
worksheet.write(6, 2, results[key][model]['2-fold']["normal "]["RMSE"][idx])
worksheet.write(7, 2, results[key][model]['3-fold']["normal "]["RMSE"][idx])
worksheet.write(8, 2, results[key][model]['4-fold']["normal "]["RMSE"][idx])
# MAE
worksheet.write(5, 4, results[key][model]['1-fold']["normal "]["MAE"][idx]) # typo: space after normal to be corrected
worksheet.write(6, 4, results[key][model]['2-fold']["normal "]["MAE"][idx])
worksheet.write(7, 4, results[key][model]['3-fold']["normal "]["MAE"][idx])
worksheet.write(8, 4, results[key][model]['4-fold']["normal "]["MAE"][idx])
# MAPE
worksheet.write(5, 6, results[key][model]['1-fold']["normal "]["MAPE"][idx])
worksheet.write(6, 6, results[key][model]['2-fold']["normal "]["MAPE"][idx])
worksheet.write(7, 6, results[key][model]['3-fold']["normal "]["MAPE"][idx])
worksheet.write(8, 6, results[key][model]['4-fold']["normal "]["MAPE"][idx])
# % Parkes AB
worksheet.write(5, 8, results[key][model]['1-fold']["normal "]["PARKES"][idx])
worksheet.write(6, 8, results[key][model]['2-fold']["normal "]["PARKES"][idx])
worksheet.write(7, 8, results[key][model]['3-fold']["normal "]["PARKES"][idx])
worksheet.write(8, 8, results[key][model]['4-fold']["normal "]["PARKES"][idx])
# % ISO
worksheet.write(5, 10, results[key][model]['1-fold']["normal "]["ISO"][idx])
worksheet.write(6, 10, results[key][model]['2-fold']["normal "]["ISO"][idx])
worksheet.write(7, 10, results[key][model]['3-fold']["normal "]["ISO"][idx])
worksheet.write(8, 10, results[key][model]['4-fold']["normal "]["ISO"][idx])
# Mean and std
rmse_mean = np.mean([results[key][model]['1-fold']["normal "]["RMSE"][idx],
results[key][model]['2-fold']["normal "]["RMSE"][idx],
results[key][model]['3-fold']["normal "]["RMSE"][idx],
results[key][model]['4-fold']["normal "]["RMSE"][idx]])
rmse_std = np.std([results[key][model]['1-fold']["normal "]["RMSE"][idx],
results[key][model]['2-fold']["normal "]["RMSE"][idx],
results[key][model]['3-fold']["normal "]["RMSE"][idx],
results[key][model]['4-fold']["normal "]["RMSE"][idx]])
text = "{:.2f}".format(rmse_mean) + "±" + "{:.2f}".format(rmse_std)
worksheet.write(9, 2, text)
mae_mean = np.mean([results[key][model]['1-fold']["normal "]["MAE"][idx],
results[key][model]['2-fold']["normal "]["MAE"][idx],
results[key][model]['3-fold']["normal "]["MAE"][idx],
results[key][model]['4-fold']["normal "]["MAE"][idx]])
mae_std = np.std([results[key][model]['1-fold']["normal "]["MAE"][idx],
results[key][model]['2-fold']["normal "]["MAE"][idx],
results[key][model]['3-fold']["normal "]["MAE"][idx],
results[key][model]['4-fold']["normal "]["MAE"][idx]])
text = "{:.2f}".format(mae_mean) + "±" + "{:.2f}".format(mae_std)
worksheet.write(9, 4, text)
mape_mean = np.mean([results[key][model]['1-fold']["normal "]["MAPE"][idx],
results[key][model]['2-fold']["normal "]["MAPE"][idx],
results[key][model]['3-fold']["normal "]["MAPE"][idx],
results[key][model]['4-fold']["normal "]["MAPE"][idx]])
mape_std = np.std([results[key][model]['1-fold']["normal "]["MAPE"][idx],
results[key][model]['2-fold']["normal "]["MAPE"][idx],
results[key][model]['3-fold']["normal "]["MAPE"][idx],
results[key][model]['4-fold']["normal "]["MAPE"][idx]])
text = "{:.2f}".format(mape_mean) + "±" + "{:.2f}".format(mape_std)
worksheet.write(9, 6, text)
parkes_mean = np.mean([results[key][model]['1-fold']["normal "]["PARKES"][idx],
results[key][model]['2-fold']["normal "]["PARKES"][idx],
results[key][model]['3-fold']["normal "]["PARKES"][idx],
results[key][model]['4-fold']["normal "]["PARKES"][idx]])
parkes_std = np.std([results[key][model]['1-fold']["normal "]["PARKES"][idx],
results[key][model]['2-fold']["normal "]["PARKES"][idx],
results[key][model]['3-fold']["normal "]["PARKES"][idx],
results[key][model]['4-fold']["normal "]["PARKES"][idx]])
text = "{:.2f}".format(parkes_mean) + "±" + "{:.2f}".format(parkes_std)
worksheet.write(9, 8, text)
iso_mean = np.mean([results[key][model]['1-fold']["normal "]["ISO"][idx],
results[key][model]['2-fold']["normal "]["ISO"][idx],
results[key][model]['3-fold']["normal "]["ISO"][idx],
results[key][model]['4-fold']["normal "]["ISO"][idx]])
iso_std = np.std([results[key][model]['1-fold']["normal "]["ISO"][idx],
results[key][model]['2-fold']["normal "]["ISO"][idx],
results[key][model]['3-fold']["normal "]["ISO"][idx],
results[key][model]['4-fold']["normal "]["ISO"][idx]])
text = "{:.2f}".format(iso_mean) + "±" + "{:.2f}".format(iso_std)
worksheet.write(9, 10, text)
elif loss == 'ISO_loss':
if model == 'naive':
pass
else:
# RMSE
worksheet.write(5, 3, results[key][model]['1-fold']["normal "]["RMSE"][idx]) # typo: space after normal to be corrected
worksheet.write(6, 3, results[key][model]['2-fold']["normal "]["RMSE"][idx])
worksheet.write(7, 3, results[key][model]['3-fold']["normal "]["RMSE"][idx])
worksheet.write(8, 3, results[key][model]['4-fold']["normal "]["RMSE"][idx])
# MAE
worksheet.write(5, 5, results[key][model]['1-fold']["normal "]["MAE"][idx])
worksheet.write(6, 5, results[key][model]['2-fold']["normal "]["MAE"][idx])
worksheet.write(7, 5, results[key][model]['3-fold']["normal "]["MAE"][idx])
worksheet.write(8, 5, results[key][model]['4-fold']["normal "]["MAE"][idx])
# MAPE
worksheet.write(5, 7, results[key][model]['1-fold']["normal "]["MAPE"][idx])
worksheet.write(6, 7, results[key][model]['2-fold']["normal "]["MAPE"][idx])
worksheet.write(7, 7, results[key][model]['3-fold']["normal "]["MAPE"][idx])
worksheet.write(8, 7, results[key][model]['4-fold']["normal "]["MAPE"][idx])
# % Parkes AB
worksheet.write(5, 9, results[key][model]['1-fold']["normal "]["PARKES"][idx])
worksheet.write(6, 9, results[key][model]['2-fold']["normal "]["PARKES"][idx])
worksheet.write(7, 9, results[key][model]['3-fold']["normal "]["PARKES"][idx])
worksheet.write(8, 9, results[key][model]['4-fold']["normal "]["PARKES"][idx])
# % ISO
worksheet.write(5, 11, results[key][model]['1-fold']["normal "]["ISO"][idx])
worksheet.write(6, 11, results[key][model]['2-fold']["normal "]["ISO"][idx])
worksheet.write(7, 11, results[key][model]['3-fold']["normal "]["ISO"][idx])
worksheet.write(8, 11, results[key][model]['4-fold']["normal "]["ISO"][idx])
# Mean and std
rmse_mean = np.mean([results[key][model]['1-fold']["normal "]["RMSE"][idx],
results[key][model]['2-fold']["normal "]["RMSE"][idx],
results[key][model]['3-fold']["normal "]["RMSE"][idx],
results[key][model]['4-fold']["normal "]["RMSE"][idx]])
rmse_std = np.std([results[key][model]['1-fold']["normal "]["RMSE"][idx],
results[key][model]['2-fold']["normal "]["RMSE"][idx],
results[key][model]['3-fold']["normal "]["RMSE"][idx],
results[key][model]['4-fold']["normal "]["RMSE"][idx]])
text = "{:.2f}".format(rmse_mean) + "±" + "{:.2f}".format(rmse_std)
worksheet.write(9, 3, text)
mae_mean = np.mean([results[key][model]['1-fold']["normal "]["MAE"][idx],
results[key][model]['2-fold']["normal "]["MAE"][idx],
results[key][model]['3-fold']["normal "]["MAE"][idx],
results[key][model]['4-fold']["normal "]["MAE"][idx]])
mae_std = np.std([results[key][model]['1-fold']["normal "]["MAE"][idx],
results[key][model]['2-fold']["normal "]["MAE"][idx],
results[key][model]['3-fold']["normal "]["MAE"][idx],
results[key][model]['4-fold']["normal "]["MAE"][idx]])
text = "{:.2f}".format(mae_mean) + "±" + "{:.2f}".format(mae_std)
worksheet.write(9, 5, text)
mape_mean = np.mean([results[key][model]['1-fold']["normal "]["MAPE"][idx],
results[key][model]['2-fold']["normal "]["MAPE"][idx],
results[key][model]['3-fold']["normal "]["MAPE"][idx],
results[key][model]['4-fold']["normal "]["MAPE"][idx]])
mape_std = np.std([results[key][model]['1-fold']["normal "]["MAPE"][idx],
results[key][model]['2-fold']["normal "]["MAPE"][idx],
results[key][model]['3-fold']["normal "]["MAPE"][idx],
results[key][model]['4-fold']["normal "]["MAPE"][idx]])
text = "{:.2f}".format(mape_mean) + "±" + "{:.2f}".format(mape_std)
worksheet.write(9, 7, text)
parkes_mean = np.mean([results[key][model]['1-fold']["normal "]["PARKES"][idx],
results[key][model]['2-fold']["normal "]["PARKES"][idx],
results[key][model]['3-fold']["normal "]["PARKES"][idx],
results[key][model]['4-fold']["normal "]["PARKES"][idx]])
parkes_std = np.std([results[key][model]['1-fold']["normal "]["PARKES"][idx],
results[key][model]['2-fold']["normal "]["PARKES"][idx],
results[key][model]['3-fold']["normal "]["PARKES"][idx],
results[key][model]['4-fold']["normal "]["PARKES"][idx]])
text = "{:.2f}".format(parkes_mean) + "±" + "{:.2f}".format(parkes_std)
worksheet.write(9, 9, text)
iso_mean = np.mean([results[key][model]['1-fold']["normal "]["ISO"][idx],
results[key][model]['2-fold']["normal "]["ISO"][idx],
results[key][model]['3-fold']["normal "]["ISO"][idx],
results[key][model]['4-fold']["normal "]["ISO"][idx]])
iso_std = np.std([results[key][model]['1-fold']["normal "]["ISO"][idx],
results[key][model]['2-fold']["normal "]["ISO"][idx],
results[key][model]['3-fold']["normal "]["ISO"][idx],
results[key][model]['4-fold']["normal "]["ISO"][idx]])
text = "{:.2f}".format(iso_mean) + "±" + "{:.2f}".format(iso_std)
worksheet.write(9, 11, text)
# save excel file
workbook.close()
os.chdir('..')
def group_best_patients_metrics(exp_config : Dict, metrics : List = ['RMSE', 'MAE', 'MAPE', '% Parkes AB', '% ISO'], results_dir : str = r"C:\Users\aralmeida\Downloads\LibreViewRawData\1yr_npy_files"):
"""
This function groups all metrics for every model for each patient
and stores their mean ± std. It return a dictionary with such
metrics.
Args:
exp_config (Dict): Dictionary with the experiment configuration (check training_configs.py) to be analyzed.
metrics (List): List with the metrics to be analyzed. Default: ['RMSE', 'MAE', 'MAPE', '% Parkes AB', '% ISO']
results_dir (str): Directory where the folders with each patient ID and the results_dictionary.json are placed.
Default:
Returns:
grouped_metrics (Dict): Dictionary with the metrics grouped by model, PH and loss function.
"""
# Go to the directory where all results are stored
os.chdir(results_dir)
# Dictionary to rearrange the metrics comfortably
grouped_metrics = {}
for model in exp_config['model']:
grouped_metrics[model] = {"30" : {}, "60" : {}}
for PH in exp_config['PH']:
for metric in metrics:
grouped_metrics[model][str(PH)][metric] = {"ISO" : {"mean" : [],
"std" : []},
"MSE" : {"mean" : [],
"std" : []}}
# Iterate over the ID folders to generate the 4-folds
for id in os.listdir():
# Consider only folders, not .npy or .txt files
if ('npy' not in id) and ('txt' not in id) and ('svg' not in id) and ('png' not in id) and ('TEST' not in id) and ('h5' not in id) and ('xls' not in id)and ('evaluation' not in id) and ('pickle' not in id):
os.chdir(id)
# Open json file
with open('results_dictionary.json') as json_file:
results = json.load(json_file)
# Iterate over PH to generate different Excel files depending on the PH (not comparable between them)
for PH in exp_config['PH']:
# Index to access the dictionary results will vary because the greater PH, the greater the index
if PH == 30:
idx = 1
elif PH == 60:
idx = 3
# Create one sheet per model
for model in exp_config['model']:
# Itreate over the loss functions and write the results
for loss in exp_config['loss_function']:
# Hard-coded to be changed
N = exp_config['N'][0]
# Obtain key to access the correspondant result
key = 'multi_N{}_step1_PH{}_month-wise-4-folds_min-max_None_{}_{}'.format(N, PH, model, loss)
if loss == 'root_mean_squared_error':
rmse_mean = np.mean([results[key][model]['1-fold']["normal "]["RMSE"][idx],
results[key][model]['2-fold']["normal "]["RMSE"][idx],
results[key][model]['3-fold']["normal "]["RMSE"][idx],
results[key][model]['4-fold']["normal "]["RMSE"][idx]])
rmse_std = np.std([results[key][model]['1-fold']["normal "]["RMSE"][idx],
results[key][model]['2-fold']["normal "]["RMSE"][idx],
results[key][model]['3-fold']["normal "]["RMSE"][idx],
results[key][model]['4-fold']["normal "]["RMSE"][idx]])
mae_mean = np.mean([results[key][model]['1-fold']["normal "]["MAE"][idx],
results[key][model]['2-fold']["normal "]["MAE"][idx],
results[key][model]['3-fold']["normal "]["MAE"][idx],
results[key][model]['4-fold']["normal "]["MAE"][idx]])
mae_std = np.std([results[key][model]['1-fold']["normal "]["MAE"][idx],
results[key][model]['2-fold']["normal "]["MAE"][idx],
results[key][model]['3-fold']["normal "]["MAE"][idx],
results[key][model]['4-fold']["normal "]["MAE"][idx]])
mape_mean = np.mean([results[key][model]['1-fold']["normal "]["MAPE"][idx],
results[key][model]['2-fold']["normal "]["MAPE"][idx],
results[key][model]['3-fold']["normal "]["MAPE"][idx],
results[key][model]['4-fold']["normal "]["MAPE"][idx]])
mape_std = np.std([results[key][model]['1-fold']["normal "]["MAPE"][idx],
results[key][model]['2-fold']["normal "]["MAPE"][idx],
results[key][model]['3-fold']["normal "]["MAPE"][idx],
results[key][model]['4-fold']["normal "]["MAPE"][idx]])
parkes_mean = np.mean([results[key][model]['1-fold']["normal "]["PARKES"][idx],
results[key][model]['2-fold']["normal "]["PARKES"][idx],
results[key][model]['3-fold']["normal "]["PARKES"][idx],
results[key][model]['4-fold']["normal "]["PARKES"][idx]])
parkes_std = np.std([results[key][model]['1-fold']["normal "]["PARKES"][idx],
results[key][model]['2-fold']["normal "]["PARKES"][idx],
results[key][model]['3-fold']["normal "]["PARKES"][idx],
results[key][model]['4-fold']["normal "]["PARKES"][idx]])
iso_mean = np.mean([results[key][model]['1-fold']["normal "]["ISO"][idx],
results[key][model]['2-fold']["normal "]["ISO"][idx],
results[key][model]['3-fold']["normal "]["ISO"][idx],
results[key][model]['4-fold']["normal "]["ISO"][idx]])
iso_std = np.std([results[key][model]['1-fold']["normal "]["ISO"][idx],
results[key][model]['2-fold']["normal "]["ISO"][idx],
results[key][model]['3-fold']["normal "]["ISO"][idx],
results[key][model]['4-fold']["normal "]["ISO"][idx]])
grouped_metrics[model][str(PH)]["RMSE"]["MSE"]["mean"].append(rmse_mean)
grouped_metrics[model][str(PH)]["MAPE"]["MSE"]["mean"].append(mape_mean)
grouped_metrics[model][str(PH)]["MAE"]["MSE"]["mean"].append(mae_mean)
grouped_metrics[model][str(PH)]["% Parkes AB"]["MSE"]["mean"].append(parkes_mean)
grouped_metrics[model][str(PH)]["% ISO"]["MSE"]["mean"].append(iso_mean)
grouped_metrics[model][str(PH)]["RMSE"]["MSE"]["std"].append(rmse_std)
grouped_metrics[model][str(PH)]["MAPE"]["MSE"]["std"].append(mape_std)
grouped_metrics[model][str(PH)]["MAE"]["MSE"]["std"].append(mae_std)
grouped_metrics[model][str(PH)]["% Parkes AB"]["MSE"]["std"].append(parkes_std)
grouped_metrics[model][str(PH)]["% ISO"]["MSE"]["std"].append(iso_std)
elif loss == 'ISO_loss':
if model == 'naive':
pass
else:
rmse_mean = np.mean([results[key][model]['1-fold']["normal "]["RMSE"][idx],
results[key][model]['2-fold']["normal "]["RMSE"][idx],
results[key][model]['3-fold']["normal "]["RMSE"][idx],
results[key][model]['4-fold']["normal "]["RMSE"][idx]])
rmse_std = np.std([results[key][model]['1-fold']["normal "]["RMSE"][idx],
results[key][model]['2-fold']["normal "]["RMSE"][idx],
results[key][model]['3-fold']["normal "]["RMSE"][idx],
results[key][model]['4-fold']["normal "]["RMSE"][idx]])
mae_mean = np.mean([results[key][model]['1-fold']["normal "]["MAE"][idx],
results[key][model]['2-fold']["normal "]["MAE"][idx],
results[key][model]['3-fold']["normal "]["MAE"][idx],
results[key][model]['4-fold']["normal "]["MAE"][idx]])
mae_std = np.std([results[key][model]['1-fold']["normal "]["MAE"][idx],
results[key][model]['2-fold']["normal "]["MAE"][idx],
results[key][model]['3-fold']["normal "]["MAE"][idx],
results[key][model]['4-fold']["normal "]["MAE"][idx]])
mape_mean = np.mean([results[key][model]['1-fold']["normal "]["MAPE"][idx],
results[key][model]['2-fold']["normal "]["MAPE"][idx],
results[key][model]['3-fold']["normal "]["MAPE"][idx],
results[key][model]['4-fold']["normal "]["MAPE"][idx]])
mape_std = np.std([results[key][model]['1-fold']["normal "]["MAPE"][idx],
results[key][model]['2-fold']["normal "]["MAPE"][idx],
results[key][model]['3-fold']["normal "]["MAPE"][idx],
results[key][model]['4-fold']["normal "]["MAPE"][idx]])
parkes_mean = np.mean([results[key][model]['1-fold']["normal "]["PARKES"][idx],
results[key][model]['2-fold']["normal "]["PARKES"][idx],
results[key][model]['3-fold']["normal "]["PARKES"][idx],
results[key][model]['4-fold']["normal "]["PARKES"][idx]])
parkes_std = np.std([results[key][model]['1-fold']["normal "]["PARKES"][idx],
results[key][model]['2-fold']["normal "]["PARKES"][idx],
results[key][model]['3-fold']["normal "]["PARKES"][idx],
results[key][model]['4-fold']["normal "]["PARKES"][idx]])
iso_mean = np.mean([results[key][model]['1-fold']["normal "]["ISO"][idx],
results[key][model]['2-fold']["normal "]["ISO"][idx],
results[key][model]['3-fold']["normal "]["ISO"][idx],
results[key][model]['4-fold']["normal "]["ISO"][idx]])
iso_std = np.std([results[key][model]['1-fold']["normal "]["ISO"][idx],
results[key][model]['2-fold']["normal "]["ISO"][idx],
results[key][model]['3-fold']["normal "]["ISO"][idx],
results[key][model]['4-fold']["normal "]["ISO"][idx]])
grouped_metrics[model][str(PH)]["RMSE"]["ISO"]["mean"].append(rmse_mean)
grouped_metrics[model][str(PH)]["MAPE"]["ISO"]["mean"].append(mape_mean)
grouped_metrics[model][str(PH)]["MAE"]["ISO"]["mean"].append(mae_mean)
grouped_metrics[model][str(PH)]["% Parkes AB"]["ISO"]["mean"].append(parkes_mean)
grouped_metrics[model][str(PH)]["% ISO"]["ISO"]["mean"].append(iso_mean)
grouped_metrics[model][str(PH)]["RMSE"]["ISO"]["std"].append(rmse_std)
grouped_metrics[model][str(PH)]["MAPE"]["ISO"]["std"].append(mape_std)
grouped_metrics[model][str(PH)]["MAE"]["ISO"]["std"].append(mae_std)
grouped_metrics[model][str(PH)]["% Parkes AB"]["ISO"]["std"].append(parkes_std)
grouped_metrics[model][str(PH)]["% ISO"]["ISO"]["std"].append(iso_std)
os.chdir('..')
return grouped_metrics
def store_global_results_in_Excel(grouped_metrics : Dict, exp_config : Dict):
"""
Store the mean ± std. of the RMSE, MAE, MAPE, % ISO and % AB Parkes
for all patients in an Excel file.
The same metrics are shown for each one of models. Notice that these are evaluation
metrics, not training metrics.
This function assumes that there is a 'results_dictonary.json' file in each patient folder, and also
assumes that the directory is provided contains folders with the ID of each patients. If these assumptions
are not correct, the function will not work.
Each studied subject has its own sheet in the corresponding directory.
Each PH (Prediction Horizon) has its own Excel file. Inside each file, there is one sheet per
evaluated model.
Args:
----
grouped_metrics (Dict): Dictionary containing all metrics organized, generated by group_best_patients_metrics()
exp_config (Dict): Dictionary with the experiment configuration wanted to be analyzed (see training_configs.py).
Returns:
-------
None
"""
# Create an unique Excel file with the overall results
workbook = xlsxwriter.Workbook('global_results.xlsx')
# Iterate over the PHs
for PH in exp_config['PH']:
# Model counters move in the Excel file
row_counter = 5 # Begin with X due to the Excel file structure
# Add worksheet corresponding to the PH
sheetname = str(PH) + 'min'
worksheet = workbook.add_worksheet(sheetname)
# Loop to fill the file
for model in exp_config['model']:
# Write the headers of the worksheet
worksheet.write(0, 0, 'PH')
worksheet.write(0, 1, str(PH)+'min')
worksheet.write(4, 1, 'Loss function')
worksheet.write(3, 2, 'RMSE')
worksheet.write(4, 2, 'MSE')
worksheet.write(4, 3, 'ISO')
worksheet.write(3, 4, 'MAE')
worksheet.write(4, 4, 'MSE')
worksheet.write(4, 5, 'ISO')
worksheet.write(3, 6, 'MAPE')
worksheet.write(4, 6, 'MSE')
worksheet.write(4, 7, 'ISO')
worksheet.write(3, 8, '% Parkes AB')
worksheet.write(4, 8, 'MSE')
worksheet.write(4, 9, 'ISO')
worksheet.write(3, 10, '% ISO')
worksheet.write(4, 10, 'MSE')
worksheet.write(4, 11, 'ISO')
# Name of current model
worksheet.write(row_counter, 1, model)
if model != 'naive':
# Compute mean and std of all metrics and place them
# MSE loss
mean = np.mean(grouped_metrics[model][str(PH)]["RMSE"]["MSE"]['mean'])
std = np.std(grouped_metrics[model][str(PH)]["RMSE"]["MSE"]['mean'])
text = "{:.2f}".format(mean) + "±" + "{:.2f}".format(std)
worksheet.write(row_counter, 2, text)
# ISO loss
mean = np.mean(grouped_metrics[model][str(PH)]["RMSE"]["ISO"]['mean'])
std = np.std(grouped_metrics[model][str(PH)]["RMSE"]["ISO"]['mean'])
text = "{:.2f}".format(mean) + "±" + "{:.2f}".format(std)
worksheet.write(row_counter, 3,text)
# MSE loss
mean = np.mean(grouped_metrics[model][str(PH)]["MAE"]["MSE"]['mean'])
std = np.std(grouped_metrics[model][str(PH)]["MAE"]["MSE"]['mean'])
text = "{:.2f}".format(mean) + "±" + "{:.2f}".format(std)
worksheet.write(row_counter, 4, text)
# ISO loss
mean = np.mean(grouped_metrics[model][str(PH)]["MAE"]["ISO"]['mean'])
std = np.std(grouped_metrics[model][str(PH)]["MAE"]["ISO"]['mean'])
text = "{:.2f}".format(mean) + "±" + "{:.2f}".format(std)
worksheet.write(row_counter, 5, text)
# MSE loss
mean = np.mean(grouped_metrics[model][str(PH)]["MAPE"]["MSE"]['mean'])
std = np.std(grouped_metrics[model][str(PH)]["MAPE"]["MSE"]['mean'])
text = "{:.2f}".format(mean) + "±" + "{:.2f}".format(std)
worksheet.write(row_counter, 6, text)
# ISO loss
mean = np.mean(grouped_metrics[model][str(PH)]["MAPE"]["ISO"]['mean'])
std = np.std(grouped_metrics[model][str(PH)]["MAPE"]["ISO"]['mean'])
text = "{:.2f}".format(mean) + "±" + "{:.2f}".format(std)
worksheet.write(row_counter, 7, text)
# MSE loss
mean = np.mean(grouped_metrics[model][str(PH)]["% Parkes AB"]["MSE"]['mean'])
std = np.std(grouped_metrics[model][str(PH)]["% Parkes AB"]["MSE"]['mean'])
text = "{:.2f}".format(mean) + "±" + "{:.2f}".format(std)
worksheet.write(row_counter, 8, text)
# ISO loss
mean = np.mean(grouped_metrics[model][str(PH)]["% Parkes AB"]["ISO"]['mean'])
std = np.std(grouped_metrics[model][str(PH)]["% Parkes AB"]["ISO"]['mean'])
text = "{:.2f}".format(mean) + "±" + "{:.2f}".format(std)
worksheet.write(row_counter, 9, text)
# MSE loss
mean = np.mean(grouped_metrics[model][str(PH)]["% ISO"]["MSE"]['mean'])
std = np.std(grouped_metrics[model][str(PH)]["% ISO"]["MSE"]['mean'])
text = "{:.2f}".format(mean) + "±" + "{:.2f}".format(std)
worksheet.write(row_counter, 10, text)
# ISO loss
mean = np.mean(grouped_metrics[model][str(PH)]["% ISO"]["ISO"]['mean'])
std = np.std(grouped_metrics[model][str(PH)]["% ISO"]["ISO"]['mean'])
text = "{:.2f}".format(mean) + "±" + "{:.2f}".format(std)
worksheet.write(row_counter, 11, text)
# Once all results are written, increment counter
row_counter = row_counter + 1
elif model == 'naive': # We don't care about the loss function since this is not trainable
# Compute mean and std of all metrics and place them
mean = np.mean(grouped_metrics[model][str(PH)]["RMSE"]["MSE"]['mean'])
std = np.std(grouped_metrics[model][str(PH)]["RMSE"]["MSE"]['mean'])
text = "{:.2f}".format(mean) + "±" + "{:.2f}".format(std)
worksheet.write(row_counter, 2, text)
worksheet.write(row_counter, 3, '-')
mean = np.mean(grouped_metrics[model][str(PH)]["MAE"]["MSE"]['mean'])
std = np.std(grouped_metrics[model][str(PH)]["MAE"]["MSE"]['mean'])
text = "{:.2f}".format(mean) + "±" + "{:.2f}".format(std)
worksheet.write(row_counter, 4, text)
worksheet.write(row_counter, 5, '-')
mean = np.mean(grouped_metrics[model][str(PH)]["MAPE"]["MSE"]['mean'])
std = np.std(grouped_metrics[model][str(PH)]["MAPE"]["MSE"]['mean'])
text = "{:.2f}".format(mean) + "±" + "{:.2f}".format(std)
worksheet.write(row_counter, 6, text)
worksheet.write(row_counter, 7, '-')
mean = np.mean(grouped_metrics[model][str(PH)]["% Parkes AB"]["MSE"]['mean'])
std = np.std(grouped_metrics[model][str(PH)]["% Parkes AB"]["MSE"]['mean'])
text = "{:.2f}".format(mean) + "±" + "{:.2f}".format(std)
worksheet.write(row_counter, 8, text)
mean = np.mean(grouped_metrics[model][str(PH)]["% ISO"]["MSE"]['mean'])
std = np.std(grouped_metrics[model][str(PH)]["% ISO"]["MSE"]['mean'])
text = "{:.2f}".format(mean) + "±" + "{:.2f}".format(std)
worksheet.write(row_counter, 10, text)
# Once all results are written, increment counter
row_counter = row_counter + 1
# Close current file
workbook.close()
def gen_PHs_boxplots(model_name : str, PH : int, iso_metrics : List, mse_metrics : List, legend : bool):
"""
Generate boxplots metric by metric separating the ISO-adapted loss from the MSE loss for a given model
Args:
----
model_name (str): model name
PH (int): Prediction Horizon
iso_metrics : List with the metrics after training with the ISO-adapted loss function
mse_metrics : List with the metrics after training with the MSE loss function
legend (bool): If True, a legend is added to the plot.
Returns:
-------
None
"""
fig, ax1 = plt.subplots(figsize=(3, 3))
metrics = ['RMSE', 'MAE', 'MAPE', 'Parkes', 'ISO']
# Set font to arial
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = 'Arial'
# Set text to bold
plt.rcParams['font.weight'] = 'bold'
plt.rcParams['axes.labelweight'] = 'bold'
box_param = dict(whis=(5, 95), widths=0.2, patch_artist=True,
flierprops=dict(marker='.', markeredgecolor='black',
fillstyle=None), medianprops=dict(color='black'))
space = 0.15
# Add title
# text = 'Model: ' + model_name + ' - PH = ' + str(PH) + ' min'
# fig.suptitle(text, fontsize=16, fontweight='bold')
ax1.boxplot(mse_metrics, positions=np.arange(len(metrics))+space,
boxprops=dict(facecolor='tab:gray'), **box_param)
ax1.set_ylim(0, 55)
# Set X ticks
labelsize = 8
ax1.set_xticks(np.arange(len(metrics)))
ax1.set_xticklabels(metrics, fontsize=20)
ax1.tick_params(axis='x', labelsize=labelsize)
# Set size to the Y labels
ax1.tick_params(axis='y', labelsize=9)
# Vertical line bewteen MAPE and Parkes
ax1.axvline(x=2.5, c='black', linestyle='--')
# Set legend
if legend:
ax1.plot([], c='tab:green', label='ISO-adapted loss')
ax1.plot([], c='tab:grey', label='MSE')
# ax1.legend(fontsize=labelsize)
ax1.legend(fontsize=7.5, loc='upper left')
# Second axis to plot metrics with different range
ax2 = ax1.twinx()
# Set y limits in both axis
ax2.boxplot(iso_metrics, positions=np.arange(len(metrics))-space,
boxprops=dict(facecolor='tab:green'), **box_param)
ax2.set_ylim(0, 105) # For ISO AND Parkes %
# Set Y ticks and labels
# ax1.set_ylabel('MAPE, MAE, RMSE', fontsize=7)
# ax2.set_ylabel('Parkes and ISO %', fontsize=7)
# Set size to the Y labels
ax2.tick_params(axis='y', labelsize=9)
# Save figure
plt.savefig('boxplot_'+model_name+'_PH_'+str(PH)+'_min.svg', format='svg', dpi=1200)
def get_patient_wise_metrics(exp_config : Dict, grouped_metrics : Dict, patients_data_folder : str = r"C:\Users\aralmeida\Downloads\LibreViewRawData-final_sims\1yr_npy_files"):
"""
In order to gain insight about which patients are "better predicted"
by the AI model, one figure per model containing one barplot per studied metric
is generated. This studied the inter-subject variability within models.
Args:
----
exp_config (Dict): Dictionary with the experiment configuration wanted to be analyzed.
grouped_metrics (Dict): Dictionary containing all metrics organized, generated by group_best_patients_metrics()
patients_data_folder : Path to the folder containing the patients' data folders
Returns:
-------
None
"""
# os.chdir(r"C:\Users\aralmeida\Downloads\LibreViewRawData\1yr_npy_files")
os.chdir(patients_data_folder)
# Get the files from dir
files = os.listdir()
patients_ids = []
for name in files:
# Only add names that are folders
if ('.npy' not in name) and ('.svg' not in name) and ('.png' not in name) and ('TEST' not in name) and ('h5' not in name) and ('xls' not in name)and ('evaluation' not in name):
# Add the name
patients_ids.append(name)
# Get the number of patients
n_patients = len(patients_ids)
# Vector of 29 positions to plot
patients_vector = np.arange(1, n_patients + 1)
# Get one figure per model-PH combination
for model in exp_config['model']:
for PH in exp_config['PH']:
fig, ax = plt.subplots(3, 2, figsize=(15,15))
# Plot bar diagram for all patients of the metric
plt.figure()
plt.suptitle(model + ' - PH = ' + str(PH) + ' min: ')
ax[0,0].bar(patients_vector, grouped_metrics[model][str(PH)]["RMSE"]["ISO"]["mean"], yerr = grouped_metrics[model][str(PH)]["RMSE"]["ISO"]["std"], color='tab:blue')
ax[0,0].set_xlabel("RMSE")
ax[0,1].bar(np.arange(1, 30), grouped_metrics[model][str(PH)]["MAPE"]["ISO"]["mean"], yerr = grouped_metrics[model][str(PH)]["MAPE"]["ISO"]["std"], color='tab:blue')
ax[0,1].set_xlabel("MAPE")
# Remove ax[1,1]
fig.delaxes(ax[1,1])
# Center and set size
ax[1,0].set_position([0.300, 0.365, 0.350, 0.25])
ax[1,0].bar(np.arange(1, 30), grouped_metrics[model][str(PH)]["MAE"]["ISO"]["mean"], yerr = grouped_metrics[model][str(PH)]["MAE"]["ISO"]["std"], color='tab:blue')
ax[1,0].set_xlabel("MAE")
ax[2,0].bar(np.arange(1, 30), grouped_metrics[model][str(PH)]["% Parkes AB"]["ISO"]["mean"], yerr = grouped_metrics[model][str(PH)]["% Parkes AB"]["ISO"]["std"], color='tab:blue')
ax[2,0].set_xlabel("% Parkes AB")
ax[2,1].bar(np.arange(1, 30), grouped_metrics[model][str(PH)]["% ISO"]["ISO"]["mean"], yerr = grouped_metrics[model][str(PH)]["% ISO"]["ISO"]["std"], color='tab:blue')
ax[2,1].set_xlabel("% ISO")
# Title
fig.suptitle(model + ' - PH = ' + str(PH) + ' min: ')
# Save figure
plt.savefig('patient-wise_'+model + '_PH_' + str(PH) + '_min.png', dpi=1200)
def get_grouped_RMSEbased_best_metrics(exp_config : Dict, grouped_metrics : Dict,
patients_data_folder : str = r"C:\Users\aralmeida\Downloads\LibreViewRawData-final_sims\1yr_npy_files"):
"""
This functions analyses the best models for each patient and return a dictionary with
the best model, loss function and the best RMSE, MAE and MAPE metric value for each patient.
These dictionaries will be used for a clear results visualizarion.
It also returns the IDs of the patients to access easily to their data. This function must be
improved. Sometimes it fails. But this function is not critical.
Args:
-----
exp_config (Dict): Dictionary with the experiment configuration wanted to be analyzed.
grouped_metrics (Dict): Dictionary containing all metrics organized, generated by group_best_patients_metrics()
patients_data_folder: folder where the patients data are stored.
Returns:
--------
best_30min_model_dict: dictionary with the best model, loss function and metric value for each patient for 30 mins.
best_60min_model_dict: dictionary with the best model, loss function and metric value for each patient for 60 mins.
patients_ids: list with the IDs of the patients.
"""
# Go to the directory where all results are stored
# os.chdir(r"C:\Users\aralmeida\Downloads\LibreViewRawData\1yr_npy_files")
os.chdir(patients_data_folder)
# Empty dictionaries and list to store the best models for each patient
best_30min_model_dict = {}
best_60min_model_dict = {}
patients_ids = []
for id in os.listdir():
# Consider only folders, not .npy or .txt files
if ('npy' not in id) and ('txt' not in id) and ('svg' not in id) and ('png' not in id) and ('TEST' not in id) and ('h5' not in id) and ('xls' not in id)and ('evaluation' not in id) and ('pickle' not in id):
patients_ids.append(id)
best_30min_model_dict[id] = {}
best_60min_model_dict[id] = {}
#####################################
# Remove '008' '011' and '007' from list
# del best_30min_model_dict['008']
# # del best_30min_model_dict['011']
# del best_30min_model_dict['007']
# del best_60min_model_dict['008']
# del best_60min_model_dict['011']
# del best_60min_model_dict['007']
# patients_ids.remove('008')
# patients_ids.remove('011')
# patients_ids.remove('007')
#####################################
# For the metric that are better of they are lower (RMSE, MAE, MAPE)
for i in range(len(patients_ids)): #num of available patients
# Fill the dictionaries once per patientd (ID)
# best_30min_model_dict[patients_ids[i]] = {"samples" : 0,
# "best_model_weights" : "",
# "RMSE": {"best_model" : "", "best_loss" : 0, "best_value" : 0},
# "MAPE": {"best_model" : "", "best_loss" : 0, "best_value" : 0},
# "MAE": {"best_model" : "", "best_loss" : 0, "best_value" : 0}}
best_60min_model_dict[patients_ids[i]] = {"samples" : 0,
"best_model_weights" : "",
"RMSE": {"best_model" : "", "best_loss" : 0, "best_value" : 0},
"MAPE": {"best_model" : "", "best_loss" : 0, "best_value" : 0},
"MAE": {"best_model" : "", "best_loss" : 0, "best_value" : 0}}
####### HARCODED #######
# Go to the id directory
dir = 'C:\\Users\\aralmeida\\Downloads\\LibreViewRawData-final_sims\\1yr_npy_files\\' + patients_ids[i] + '\\N96\step1\\PH30\\multi\\month-wise-4-folds\\norm_min-max\\None_sampling\\DIL-1D-UNET\\ISO_loss'
os.chdir(dir)
#######################
# Load the X.npy that contains all the instances used to train the data
oldest_1yr_CGM = np.load('X.npy')
shape = oldest_1yr_CGM.shape[0]
# Iterate over the metrics to generate one graph per metric
for metric in ['RMSE', 'MAPE', 'MAE']:
counter_30 = 0
counter_60 = 0
for models in exp_config["model"]:
for loss in ["ISO", "MSE"]: # harcoded: the studied loss functions
# Update the metric with each iteration
# 60 mins
# Naive is different because it doesn't have a loss function
if models == 'naive':
curr_metric_60 = grouped_metrics[models]["60"][metric]["MSE"]["mean"][i]
curr_loss_func_60 = "MSE"
curr_model_60 = models
# curr_metric_30 = grouped_metrics[models]["30"][metric]["MSE"]["mean"][i]
# curr_loss_func_30 = "MSE"
# curr_model_30 = models
else:
curr_metric_60 = grouped_metrics[models]["60"][metric][loss]["mean"][i]
curr_loss_func_60 = loss
curr_model_60 = models
if counter_30 == 0 and counter_60 == 0:
# best_metric_30 = curr_metric_30
# best_loss_func_30 = curr_loss_func_30
# best_model_30 = curr_model_30
best_metric_60 = curr_metric_60
best_loss_func_60 = curr_loss_func_60
best_model_60 = curr_model_60
# best_30min_model_dict[patients_ids[i]]["samples"] = shape
# best_30min_model_dict[patients_ids[i]][metric]["best_model"] = best_model_30
# best_30min_model_dict[patients_ids[i]][metric]["best_loss"] = best_loss_func_30
# best_30min_model_dict[patients_ids[i]][metric]["best_value"] = best_metric_30
best_60min_model_dict[patients_ids[i]]["samples"] = shape
best_60min_model_dict[patients_ids[i]][metric]["best_model"] = best_model_60
best_60min_model_dict[patients_ids[i]][metric]["best_loss"] = best_loss_func_60
best_60min_model_dict[patients_ids[i]][metric]["best_value"] = best_metric_60
counter_30 = counter_30+1
# counter_60 = counter_60+1
else: