-
Notifications
You must be signed in to change notification settings - Fork 0
/
callbacks.py
2244 lines (2186 loc) · 104 KB
/
callbacks.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 dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, State, Output
from dash.exceptions import PreventUpdate
from dash import callback_context
import pandas as pd
import data_utils as du
from model_interpreter.model_interpreter import ModelInterpreter
import plotly.graph_objs as go
import Models
import torch
import numpy as np
from time import time
import yaml
import inspect
import random
from flask_caching import Cache
from app import app
import layouts
# Set the random seed for reproducibility:
du.set_random_seed(42)
# Path to the directory where all the ML models are stored
models_path = 'models/'
# Path to the directory where all the ML model metrics are stored
metrics_path = 'metrics/'
# Path to the normalization stats
norm_stats_path = ''
# [TODO] Set and update whether the model is from a custom type or not
is_custom = True
# Padding value used to pad the data sequences up to a maximum length
padding_value = 999999
# Time threshold to prevent updates during this seconds after clicking in a data point
clicked_thrsh = 5
# Load the model descriptions file
descriptions_stream = open(f'{models_path}model_descriptions.yml', 'r')
descriptions = yaml.load(descriptions_stream, Loader=yaml.FullLoader)
# Setup cache
cache = Cache(app.server, config={
'CACHE_TYPE': 'filesystem',
'CACHE_DIR': 'cache/'
})
# Only reset cache after one week
TIMEOUT = 604800
# Index callback
@app.callback(Output('page-content', 'children'),
[Input('url', 'pathname')])
def display_page(pathname):
if pathname == '/':
return layouts.main_layout
elif pathname == '/performance':
return layouts.performance_layout
elif pathname == '/dataset-overview':
return layouts.dataset_overview_layout
elif pathname == '/feature-importance':
return layouts.feat_import_layout
elif pathname == '/detailed-analysis':
return layouts.detail_analysis_layout
else:
return '404'
# Loading data callbacks
def load_dataset(file_name, file_path='', file_ext='.csv',
id_column='subject_id', ts_column='ts'):
# Read the dataframe
df = pd.read_csv(f'{file_path}{file_name}{file_ext}')
df = df.drop(columns='Unnamed: 0')
# Optimize the column data types
df[id_column] = df[id_column].astype('uint')
df[ts_column] = df[ts_column].astype('int')
return df
@app.callback([Output('dataset_store', 'data'),
Output('id_col_name_store', 'data'),
Output('ts_col_name_store', 'data'),
Output('label_col_name_store', 'data'),
Output('cols_to_remove_store', 'data'),
Output('reset_data_bttn', 'disabled'),
Output('total_length_store', 'data'),
Output('norm_stats_store', 'data')],
[Input('dataset_name_div', 'children'),
Input('sample_table', 'data_timestamp'),
Input('model_store', 'data'),
Input('reset_data_bttn', 'n_clicks')],
[State('sample_table', 'data'),
State('dataset_store', 'data')])
def load_dataset_callback(dataset_name, dataset_mod, model_file_name,
reset_clicks, new_data, dataset_store):
if callback_context.triggered[0]['prop_id'].split('.')[0] != 'sample_table':
# Loading a dataset from disk
if dataset_name == 'ALS':
data_path = 'data/ALS/'
data_file_name = f'fcul_als_with_shap_for_{model_file_name}'
id_column = 'subject_id'
ts_column = 'ts'
label_column = 'niv_label'
stream_norm_stats = open(f'{data_path}norm_stats.yml', 'r')
elif dataset_name == 'Toy Example':
data_path = 'data/ToyExample/'
data_file_name = f'toy_example_with_shap_for_{model_file_name}'
id_column = 'subject_id'
ts_column = 'ts'
label_column = 'label'
stream_norm_stats = open(f'{data_path}norm_stats.yml', 'r')
else:
raise Exception(f'ERROR: The HAI dashboarded isn\'t currently suited to load the dataset named {dataset_name}.')
df = load_dataset(file_name=data_file_name, file_path=data_path,
file_ext='.csv', id_column=id_column)
# Calculate the maximum sequence length
total_length = df.groupby(id_column)[ts_column].count().max()
# Load the normalization statistics
norm_stats = yaml.load(stream_norm_stats, Loader=yaml.FullLoader)
return df.to_dict('records'), id_column, ts_column, label_column, [0, 1], True, total_length, norm_stats
else:
if dataset_name == 'ALS':
data_path = 'data/ALS/'
id_column = 'subject_id'
ts_column = 'ts'
label_column = 'niv_label'
stream_norm_stats = open(f'{data_path}norm_stats.yml', 'r')
elif dataset_name == 'Toy Example':
data_path = 'data/ToyExample/'
id_column = 'subject_id'
ts_column = 'ts'
label_column = 'label'
stream_norm_stats = open(f'{data_path}norm_stats.yml', 'r')
# Refreshing the data with a new edited sample
df = apply_data_changes(new_data, dataset_store, id_column=id_column,
ts_column=ts_column, label_column=label_column,
model_file_name=model_file_name,
dataset_name=dataset_name)
# Calculate the maximum sequence length
total_length = df.groupby(id_column)[ts_column].count().max()
# Load the normalization statistics
norm_stats = yaml.load(stream_norm_stats, Loader=yaml.FullLoader)
return df.to_dict('records'), id_column, ts_column, label_column, [0, 1], False, total_length, norm_stats
@app.callback([Output('model_store', 'data'),
Output('model_metrics', 'data'),
Output('model_hyperparam', 'data'),
Output('is_custom_store', 'data')],
[Input('model_name_div', 'children'),
Input('dataset_name_div', 'children')])
def load_model_callback(model_name, dataset_name):
global models_path
global metrics_path
# Based on the chosen dataset and model type, set a file path to the desired model
if dataset_name == 'ALS':
subdata_path = 'ALS/'
if model_name == 'Bidir LSTM, time aware':
# Specify the model file name and class
model_file_name = 'lstm_bidir_one_hot_encoded_delta_ts_90dayswindow_0.3784valloss_08_07_2020_04_14'
model_class = Models.VanillaLSTM
is_custom = False
elif model_name == 'Bidir LSTM, embedded':
# Specify the model file name and class
model_file_name = 'lstm_bidir_pre_embedded_90dayswindow_0.2490valloss_06_07_2020_03_47'
model_class = Models.VanillaLSTM
is_custom = False
elif model_name == 'Bidir LSTM':
# Specify the model file name and class
model_file_name = 'lstm_bidir_one_hot_encoded_90dayswindow_0.4497valloss_08_07_2020_04_31'
model_class = Models.VanillaLSTM
is_custom = False
elif model_name == 'Bidir LSTM, embedded, time aware':
# Specify the model file name and class
model_file_name = 'lstm_bidir_pre_embedded_delta_ts_90dayswindow_0.3705valloss_08_07_2020_04_04'
model_class = Models.VanillaLSTM
is_custom = False
elif model_name == 'LSTM':
# Specify the model file name and class
model_file_name = 'lstm_one_hot_encoded_90dayswindow_0.5125valloss_08_07_2020_04_41'
model_class = Models.VanillaLSTM
is_custom = False
elif model_name == 'Bidir RNN, embedded, time aware':
# Specify the model file name and class
model_file_name = 'rnn_bidir_pre_embedded_delta_ts_90dayswindow_0.3579valloss_08_07_2020_03_55'
model_class = Models.VanillaRNN
is_custom = False
elif model_name == 'Bidir RNN':
# Specify the model file name and class
model_file_name = 'rnn_bidir_one_hot_encoded_90dayswindow_0.3713valloss_08_07_2020_04_49'
model_class = Models.VanillaRNN
is_custom = False
elif model_name == 'RNN, time aware':
# Specify the model file name and class
model_file_name = 'rnn_one_hot_encoded_delta_ts_90dayswindow_0.5354valloss_21_08_2020_04_24'
model_class = Models.VanillaRNN
is_custom = False
elif model_name == 'RNN':
# Specify the model file name and class
model_file_name = 'rnn_one_hot_encoded_90dayswindow_0.5445valloss_21_08_2020_04_34'
model_class = Models.VanillaRNN
is_custom = False
elif model_name == 'MF1-LSTM':
# Specify the model file name and class
model_file_name = 'mf1lstm_one_hot_encoded_90dayswindow_0.6009valloss_07_07_2020_03_46'
model_class = Models.MF1LSTM
is_custom = True
elif dataset_name == 'Toy Example':
subdata_path = 'ToyExample/'
# [TODO] Train and add each model for the toy example
if model_name == 'Bidir LSTM, embedded, time aware':
# Specify the model file name and class
model_file_name = ''
model_class = Models.VanillaLSTM
is_custom = False
elif model_name == 'Bidir LSTM, time aware':
# Specify the model file name and class
model_file_name = ''
model_class = Models.VanillaLSTM
is_custom = False
elif model_name == 'Bidir LSTM, embedded':
# Specify the model file name and class
model_file_name = ''
model_class = Models.VanillaLSTM
is_custom = False
elif model_name == 'LSTM':
# Specify the model file name and class
model_file_name = ''
model_class = Models.VanillaLSTM
is_custom = False
elif model_name == 'Bidir RNN, embedded, time aware':
# Specify the model file name and class
model_file_name = ''
model_class = Models.VanillaRNN
is_custom = False
elif model_name == 'RNN, embedded':
# Specify the model file name and class
model_file_name = ''
model_class = Models.VanillaRNN
is_custom = False
elif model_name == 'RNN':
# Specify the model file name and class
model_file_name = ''
model_class = Models.VanillaRNN
is_custom = False
elif model_name == 'MF1-LSTM':
# Specify the model file name and class
model_file_name = ''
model_class = Models.MF1LSTM
is_custom = True
else:
raise Exception(f'ERROR: The HAI dashboarded isn\'t currently suited to load the dataset named {dataset_name}.')
# Load the metrics file
metrics_stream = open(f'{metrics_path}{subdata_path}individual_models/{model_file_name}.yml', 'r')
metrics = yaml.load(metrics_stream, Loader=yaml.FullLoader)
# Register all the hyperparameters
model = du.deep_learning.load_checkpoint(filepath=f'{models_path}{subdata_path}{model_file_name}.pth',
ModelClass=model_class)
model_args = inspect.getfullargspec(model.__init__).args[1:]
hyperparams = dict([(param, str(getattr(model, param)))
for param in model_args])
return (model_file_name,
metrics,
hyperparams,
is_custom)
@app.callback(Output('model_description_list', 'children'),
[Input('model_store', 'modified_timestamp')],
[State('model_store', 'data')])
def load_model_description(model_mod, model_file_name):
global descriptions
description_list = list()
# Add model type description
if 'mf1lstm' in model_file_name:
description_list.append(dbc.ListGroupItem(descriptions['model_type']['MF1-LSTM']))
elif 'lstm' in model_file_name:
description_list.append(dbc.ListGroupItem(descriptions['model_type']['LSTM']))
elif 'rnn' in model_file_name:
description_list.append(dbc.ListGroupItem(descriptions['model_type']['RNN']))
# Add direction description
if 'bidir' in model_file_name:
description_list.append(dbc.ListGroupItem(descriptions['bidir']['is bidirectional']))
else:
description_list.append(dbc.ListGroupItem(descriptions['bidir']['single direction']))
# Add embedding description
if 'pre_embedded' in model_file_name:
description_list.append(dbc.ListGroupItem(descriptions['embedding']['pre-embedded']))
elif 'with_embedding' in model_file_name:
description_list.append(dbc.ListGroupItem(descriptions['embedding']['with embedding']))
else:
description_list.append(dbc.ListGroupItem(descriptions['embedding']['one hot encoded']))
# Add time variation description
if 'mf1lstm' in model_file_name:
description_list.append(dbc.ListGroupItem(descriptions['delta_ts']['integrates_in_model']))
elif 'delta_ts' in model_file_name:
description_list.append(dbc.ListGroupItem(descriptions['delta_ts']['uses delta_ts']))
else:
description_list.append(dbc.ListGroupItem(descriptions['delta_ts']['no delta_ts']))
return description_list
@app.callback(Output('hyperparam_table', 'children'),
[Input('model_hyperparam', 'modified_timestamp')],
[State('model_hyperparam', 'data')])
def load_hyperparameters(hyperparam_mod, hyperparams):
rows = list()
for key, val in hyperparams.items():
# Add each table row, corresponding to each hyperparameter
rows.append(html.Tr([html.Td(key), html.Td(val)]))
return rows
@app.callback(Output('metrics_table', 'children'),
[Input('model_metrics', 'modified_timestamp')],
[State('model_metrics', 'data')])
def load_metrics(metrics_mod, metrics):
rows = list()
# Add the table header
rows.append(html.Thead(html.Tr([html.Th('Metric'), html.Th('Train'), html.Th('Val'), html.Th('Test')])))
for key, value in metrics['test'].items():
# Get the values
train_value = metrics['train'][key]
val_value = metrics['val'][key]
test_value = metrics['test'][key]
# Configure the plot, according to the metrics type
if key == 'accuracy' or key == 'precision' or key == 'recall':
train_value = train_value * 100
val_value = val_value * 100
test_value = test_value * 100
max_val = 100
higher_is_better = True
suffix = '%'
elif key == 'loss':
# Using a fictional maximum loss of 1.3, as usually a loss that
# big is associated with a bad model performance
max_val = 1.3
higher_is_better = False
suffix = None
else:
max_val = 1
higher_is_better = True
suffix = None
# Add each table row, corresponding to each metric
rows.append(html.Tr([
html.Td(key),
html.Td(
du.visualization.indicator_plot(train_value, min_val=0, max_val=max_val,
type='bullet',
higher_is_better=higher_is_better,
background_color=layouts.colors['gray_background'],
dash_id=f'train_{key}_indicator',
font_color=layouts.colors['body_font_color'],
suffix=suffix, output_type='dash',
dash_height='1.5em', animate=True),
style=dict(width='30%')
),
html.Td(
du.visualization.indicator_plot(val_value, min_val=0, max_val=max_val,
type='bullet',
higher_is_better=higher_is_better,
background_color=layouts.colors['gray_background'],
dash_id=f'val_{key}_indicator',
font_color=layouts.colors['body_font_color'],
suffix=suffix, output_type='dash',
dash_height='1.5em', animate=True),
style=dict(width='30%')
),
html.Td(
du.visualization.indicator_plot(test_value, min_val=0, max_val=max_val,
type='bullet',
higher_is_better=higher_is_better,
background_color=layouts.colors['gray_background'],
dash_id=f'test_{key}_indicator',
font_color=layouts.colors['body_font_color'],
suffix=suffix, output_type='dash',
dash_height='1.5em', animate=True),
style=dict(width='30%')
)
]))
return rows
# Dropdown callbacks
@app.callback(Output('dataset_name_div', 'children'),
[Input('dataset_dropdown', 'value')])
def change_dataset(dataset):
return dataset
@app.callback(Output('model_name_div', 'children'),
[Input('model_dropdown', 'value')])
def change_model_name(model_name):
return model_name
# Button callbacks
@app.callback(Output('edit_sample_bttn', 'children'),
[Input('edit_sample_bttn', 'n_clicks')])
def update_edit_button(n_clicks):
if n_clicks % 2 == 0:
return 'Edit sample'
else:
return 'Stop editing'
@app.callback([Output('sample_table', 'columns'),
Output('sample_table', 'data'),
Output('sample_edit_div', 'hidden'),
Output('sample_edit_card_title', 'children')],
[Input('edit_sample_bttn', 'n_clicks')],
[State('dataset_store', 'data'),
State('id_col_name_store', 'data'),
State('ts_col_name_store', 'data'),
State('label_col_name_store', 'data'),
State('instance_importance_graph', 'hoverData'),
State('instance_importance_graph', 'clickData'),
State('clicked_ts', 'children'),
State('hovered_ts', 'children'),
State('model_store', 'data')])
def update_sample_table(n_clicks, dataset_store, id_column, ts_column, label_column,
hovered_data, clicked_data, clicked_ts, hovered_ts,
model_file_name):
if n_clicks % 2 == 0 or (hovered_data is None and clicked_data is None):
# Stop editing
return None, None, True, 'Sample from patient Y on timestamp X'
# raise PreventUpdate
else:
global clicked_thrsh
clicked_ts = int(clicked_ts)
hovered_ts = int(hovered_ts)
# Reconvert the dataframe to Pandas
df = pd.DataFrame(dataset_store)
# Check whether the current sample has originated from a hover or a click event
if (hovered_ts - clicked_ts) <= clicked_thrsh:
# Get the selected data point's subject ID and timestamp
subject_id = int(clicked_data['points'][0]['y'])
ts = clicked_data['points'][0]['x']
else:
# Get the selected data point's subject ID and timestamp
subject_id = int(hovered_data['points'][0]['y'])
ts = hovered_data['points'][0]['x']
# Filter by the selected data point
filtered_df = df.copy()
filtered_df = filtered_df[(filtered_df[id_column] == subject_id)
& (filtered_df[ts_column] == ts)]
# Remove SHAP values and other unmodifiable columns from the table
shap_column_names = [feature for feature in filtered_df.columns
if feature.endswith('_shap')]
filtered_df.drop(columns=shap_column_names, inplace=True)
filtered_df.drop(columns=label_column, inplace=True)
if 'delta_ts' in filtered_df.columns:
filtered_df.drop(columns='delta_ts', inplace=True)
# Set the column names as a list of dictionaries, as data table requires
columns = filtered_df.columns
data_columns = [dict(name=column, id=column) for column in columns]
return (data_columns, filtered_df.to_dict('records'), False,
f'Sample from patient {subject_id} on timestamp {ts}')
@app.callback(Output('feature_importance_dropdown', 'options'),
[Input('dataset_store', 'modified_timestamp')],
[State('dataset_store', 'data')])
def load_feat_import_filter_options(dataset_mod, dataset_store):
# Reconvert the dataframe to Pandas
df = pd.DataFrame(dataset_store)
# Get the list of columns without the identifier and the feature importance columns
shap_column_names = [feature for feature in df.columns
if feature.endswith('_shap')]
feature_names = [feature.split('_shap')[0] for feature in shap_column_names]
# Create the feature dropdown filter
options = list()
options.append(dict(label='All', value='All'))
[options.append(dict(label=feat, value=feat)) for feat in feature_names]
return options
# Page headers callbacks
@app.callback(Output('model_perf_header', 'children'),
[Input('model_name_div', 'children')])
def change_performance_header(model_name):
return model_name
@app.callback(Output('dataset_ovrvw_header', 'children'),
[Input('dataset_name_div', 'children')])
def change_dataset_header(dataset):
return dataset
@app.callback(Output('main_title', 'children'),
[Input('dataset_name_div', 'children'),
Input('model_name_div', 'children')])
def change_title(dataset_name, model_name):
if dataset_name == 'ALS':
label_name = 'NIV'
elif dataset_name == 'Toy Example':
label_name == 'mortality'
else:
raise Exception(f'ERROR: The HAI dashboarded isn\'t currently suited to load the dataset named {dataset_name}.')
return f'{dataset_name} {label_name} prediction with {model_name} model'
# Detailed analysis strings
@app.callback(Output('clicked_ts', 'children'),
[Input('instance_importance_graph', 'clickData')])
def update_clicked_ts(clicked_data):
return str(int(time()))
@app.callback(Output('hovered_ts', 'children'),
[Input('instance_importance_graph', 'hoverData')])
def update_hovered_ts(hovered_data):
return str(int(time()))
@app.callback(Output('salient_features_card_title', 'children'),
[Input('instance_importance_graph', 'hoverData'),
Input('instance_importance_graph', 'clickData')],
[State('clicked_ts', 'children')])
def update_patient_salient_feat_title(hovered_data, clicked_data, clicked_ts):
global clicked_thrsh
current_ts = time()
clicked_ts = int(clicked_ts)
# Check whether the trigger was the hover or click event
if callback_context.triggered[0]['prop_id'].split('.')[1] == 'hoverData':
if (current_ts - clicked_ts) <= clicked_thrsh:
# Prevent the card from being updated on hover data if a
# data point has been clicked recently
raise PreventUpdate
# Get the selected data point's subject ID
subject_id = hovered_data['points'][0]['y']
else:
# Get the selected data point's subject ID
subject_id = clicked_data['points'][0]['y']
return f'Patient {subject_id}\'s salient features'
@app.callback(Output('ts_feature_importance_card_title', 'children'),
[Input('instance_importance_graph', 'hoverData'),
Input('instance_importance_graph', 'clickData')],
[State('clicked_ts', 'children')])
def update_ts_feat_import_title(hovered_data, clicked_data, clicked_ts):
global clicked_thrsh
current_ts = time()
clicked_ts = int(clicked_ts)
# Check whether the trigger was the hover or click event
if callback_context.triggered[0]['prop_id'].split('.')[1] == 'hoverData':
if (current_ts - clicked_ts) <= clicked_thrsh:
# Prevent the card from being updated on hover data if a
# data point has been clicked recently
raise PreventUpdate
# Get the selected data point's timestamp
ts = hovered_data['points'][0]['x']
else:
# Get the selected data point's timestamp
ts = clicked_data['points'][0]['x']
return f'Feature importance on ts={ts}'
@app.callback([Output('patient_outcome_text', 'children'),
Output('patient_outcome_card', 'color')],
[Input('instance_importance_graph', 'hoverData'),
Input('instance_importance_graph', 'clickData')],
[State('clicked_ts', 'children'),
State('dataset_store', 'data'),
State('dataset_name_div', 'children'),
State('id_col_name_store', 'data'),
State('ts_col_name_store', 'data'),
State('label_col_name_store', 'data')])
def update_patient_outcome(hovered_data, clicked_data, clicked_ts,
dataset_store, dataset_name, id_column,
ts_column, label_column):
global clicked_thrsh
current_ts = time()
clicked_ts = int(clicked_ts)
# Reconvert the dataframe to Pandas
df = pd.DataFrame(dataset_store)
# Check whether the trigger was the hover or click event
if callback_context.triggered[0]['prop_id'].split('.')[1] == 'hoverData':
if (current_ts - clicked_ts) <= clicked_thrsh:
# Prevent the card from being updated on hover data if a
# data point has been clicked recently
raise PreventUpdate
# Get the selected data point's subject ID
subject_id = int(hovered_data['points'][0]['y'])
else:
# Get the selected data point's subject ID
subject_id = int(clicked_data['points'][0]['y'])
# Filter by the selected data point
filtered_df = df.copy()
filtered_df = filtered_df[filtered_df[id_column] == subject_id]
# Find if the patient dies
patient_dies = (filtered_df.tail(1)[label_column] == 1).values[0]
if patient_dies == True:
if dataset_name == 'ALS':
outcome = 'Patient ends up using NIV'
else:
outcome = 'Patient dies'
card_color = 'danger'
else:
if dataset_name == 'ALS':
outcome = 'Patient doesn\'t end using NIV'
else:
outcome = 'Patient survives'
card_color = 'success'
return outcome, card_color
# Plotting
@app.callback([Output('test_accuracy_indicator_preview', 'figure'),
Output('test_auc_indicator_preview', 'figure'),
Output('test_f1_indicator_preview', 'figure')],
[Input('model_metrics', 'modified_timestamp')],
[State('model_metrics', 'data')])
def update_performance_preview(metrics_mod, metrics):
# Get the values
acc = metrics['test']['accuracy']
auc = metrics['test']['AUC']
f1 = metrics['test']['F1']
# Accuracy plot
acc = acc * 100
acc_plot = du.visualization.indicator_plot(acc, min_val=0, max_val=100,
type='bullet',
higher_is_better=True,
background_color=layouts.colors['gray_background'],
font_color=layouts.colors['body_font_color'],
suffix='%', output_type='plotly')
# AUC plot
auc_plot = du.visualization.indicator_plot(auc, min_val=0, max_val=1,
type='bullet',
higher_is_better=True,
background_color=layouts.colors['gray_background'],
font_color=layouts.colors['body_font_color'],
suffix=None, output_type='plotly')
# F1 plot
f1_plot = du.visualization.indicator_plot(f1, min_val=0, max_val=1,
type='bullet',
higher_is_better=True,
background_color=layouts.colors['gray_background'],
font_color=layouts.colors['body_font_color'],
suffix=None, output_type='plotly')
return acc_plot, auc_plot, f1_plot
@app.callback(Output('test_auc_gauge', 'figure'),
[Input('model_metrics', 'modified_timestamp')],
[State('model_metrics', 'data')])
def render_auc_gauge(metrics_mod, metrics):
return du.visualization.indicator_plot(metrics['test']['AUC'], min_val=0, max_val=1,
type='gauge',
background_color=layouts.colors['gray_background'],
font_color=layouts.colors['header_font_color'],
font_size=20,
output_type='plotly')
@app.callback(Output('dataset_preview', 'children'),
[Input('dataset_store', 'modified_timestamp'),
Input('norm_stats_store', 'modified_timestamp'),
Input('label_col_name_store', 'modified_timestamp')],
[State('dataset_store', 'data'),
State('norm_stats_store', 'data'),
State('label_col_name_store', 'data')])
def update_dataset_preview(dataset_mod, norm_stats_mod, label_column_mod,
dataset_store, norm_stats, label_column):
if norm_stats is None or label_column is None:
# Don't update the plot if any of the required inputs have not been defined yet
raise PreventUpdate
# Reconvert the dataframe to Pandas
df = pd.DataFrame(dataset_store)
# Get the average age
avg_age = int(norm_stats['age_at_onset']['mean'])
# Calculate the percentage of patients with gender 0
gender_counts = df.gender.value_counts()
gender_0_percent = (gender_counts[0] / (gender_counts.sum())) * 100
gender_0_percent = f'{gender_0_percent:.2f}%'
# Calculate the label activations per sample percentage
label_count = df[label_column].value_counts()
label_act = (label_count[1] / (label_count.sum())) * 100
label_act = f'{label_act:.2f}%'
# Create the rows
rows = [
dbc.Row([
dbc.Col(html.Div('Average age'), width=6),
dbc.Col(html.Div(avg_age), width=6)
], style=dict(
height='2em',
marginTop='1em'
)),
dbc.Row([
dbc.Col(html.Div('Patients of gender 0'), width=6),
dbc.Col(html.Div(gender_0_percent), width=6)
], style=dict(
height='2em',
marginTop='1em'
)),
dbc.Row([
dbc.Col(html.Div('Label activations per sample'), width=6),
dbc.Col(html.Div(label_act), width=6)
], style=dict(
height='2em',
marginTop='1em',
marginBottom='2.5em'
)),
]
return rows
def create_num_patients_card(df, id_column, card_height=None, card_width=None, font_size=20):
style = dict()
if card_height is not None:
style['height'] = card_height
if card_width is not None:
style['width'] = card_width
# Count the number of patients
n_patients = df[id_column].nunique()
# Get the indicator plot
num_patients_plot = du.visualization.indicator_plot(n_patients,
show_graph=False,
background_color=layouts.colors['gray_background'],
font_color=layouts.colors['header_font_color'],
font_size=font_size,
output_type='dash',
dash_height='5em')
# Create the card
num_patients_card = dbc.Card([
dbc.CardBody([
num_patients_plot,
html.H5('patients', style=dict(textAlign='center'))
])
], style=style)
return num_patients_card
def create_num_feat_card(df, card_height=None, card_width=None, font_size=20):
style = dict()
if card_height is not None:
style['height'] = card_height
if card_width is not None:
style['width'] = card_width
# Get the list of columns without the identifier and the feature importance columns
shap_column_names = [feature for feature in df.columns
if feature.endswith('_shap')]
feature_names = [feature.split('_shap')[0] for feature in shap_column_names]
# Count the number of features
n_features = len(feature_names)
# Get the indicator plot
num_features_plot = du.visualization.indicator_plot(n_features,
show_graph=False,
background_color=layouts.colors['gray_background'],
font_color=layouts.colors['header_font_color'],
font_size=font_size,
output_type='dash',
dash_height='5em')
# Create the card
num_features_card = dbc.Card([
dbc.CardBody([
num_features_plot,
html.H5('features', style=dict(textAlign='center'))
])
], style=style)
return num_features_card
def create_num_rows_card(df, card_height=None, card_width=None, font_size=20):
style = dict()
if card_height is not None:
style['height'] = card_height
if card_width is not None:
style['width'] = card_width
# Count the number of rows
n_rows = len(df)
# Get the indicator plot
num_rows_plot = du.visualization.indicator_plot(n_rows,
show_graph=False,
background_color=layouts.colors['gray_background'],
font_color=layouts.colors['header_font_color'],
font_size=font_size,
output_type='dash',
dash_height='5em')
# Create the card
num_rows_card = dbc.Card([
dbc.CardBody([
num_rows_plot,
html.H5('rows', style=dict(textAlign='center'))
])
], style=style)
return num_rows_card
def create_num_data_points_card(df, card_height=None, card_width=None, font_size=20):
style = dict()
if card_height is not None:
style['height'] = card_height
if card_width is not None:
style['width'] = card_width
# Count the number of rows
n_rows = len(df)
# Get the list of columns without the feature importance columns
shap_column_names = [feature for feature in df.columns
if feature.endswith('_shap')]
column_names = list(df.columns)
[column_names.remove(shap_column) for shap_column in shap_column_names]
# Count the number of columns
n_columns = len(column_names)
# Calculate the number of data points
n_data_points = n_rows * n_columns
# Get the indicator plot
num_data_points_plot = du.visualization.indicator_plot(n_data_points,
show_graph=False,
background_color=layouts.colors['gray_background'],
font_color=layouts.colors['header_font_color'],
font_size=font_size,
output_type='dash',
dash_height='5em')
# Create the card
num_data_points_card = dbc.Card([
dbc.CardBody([
num_data_points_plot,
html.H5('data points', style=dict(textAlign='center'))
])
], style=style)
return num_data_points_card
def create_dataset_size_card(df, card_height=None, card_width=None, font_size=20):
style = dict()
if card_height is not None:
style['height'] = card_height
if card_width is not None:
style['width'] = card_width
# Convert the dataframe's columns to more efficient types
df = df.convert_dtypes()
# Calculate the memory size of the dataframe, in MB
data_size = df.memory_usage(index=True, deep=True)
data_size = data_size.sum()
data_size = int(data_size / pow(10, 6))
# Get the indicator plot
data_size_plot = du.visualization.indicator_plot(data_size,
show_graph=False,
background_color=layouts.colors['gray_background'],
font_color=layouts.colors['header_font_color'],
font_size=font_size,
output_type='dash',
dash_height='5em',
suffix=' MB')
# Create the card
data_size_card = dbc.Card([
dbc.CardBody([
data_size_plot,
html.H5('dataset size', style=dict(textAlign='center'))
])
], style=style)
return data_size_card
def create_avg_seq_len_card(df, id_column, ts_column, card_height=None, card_width=None, font_size=20):
style = dict()
if card_height is not None:
style['height'] = card_height
if card_width is not None:
style['width'] = card_width
# Calculate the average sequence length
avg_seq_len = int(df.groupby(id_column)[ts_column].count().mean())
# Get the indicator plot
num_avg_seq_len_plot = du.visualization.indicator_plot(avg_seq_len,
show_graph=False,
background_color=layouts.colors['gray_background'],
font_color=layouts.colors['header_font_color'],
font_size=font_size,
output_type='dash',
dash_height='5em')
#
# Create the card
num_avg_seq_len_card = dbc.Card([
dbc.CardBody([
num_avg_seq_len_plot,
html.H5('average sequence length', style=dict(textAlign='center'))
])
], style=style)
return num_avg_seq_len_card
def create_seq_len_hist_card(df, id_column, ts_column, selected_feat='All', card_height=None, card_width=None, font_size=20):
style = dict()
if card_height is not None:
style['height'] = card_height
if card_width is not None:
style['width'] = card_width
if selected_feat == 'All' or selected_feat == None:
# Calculate the sequence lengths on this subset of data
seq_len = df.groupby(id_column)[ts_column].count()
# Configure the plot
data = [
go.Histogram(
x=seq_len,
y=seq_len.index,
name='All'
)
]
layout = go.Layout(
title_text='Sequence length distribution',
xaxis_title_text='Sequence length',
yaxis_title_text='Count',
paper_bgcolor=layouts.colors['gray_background'],
plot_bgcolor=layouts.colors['gray_background'],
margin=dict(l=0, r=0, t=50, b=0, pad=0),
font=dict(
family='Roboto',
size=font_size,
color=layouts.colors['header_font_color']
)
)
else:
# Find the unique values of a column
unique_vals = df[selected_feat].unique()
# Create an histogram for each segment of data that matches each unique value
data = list()
for val in unique_vals:
# Get the data that has the current value
tmp_df = df[df[selected_feat] == val]
# Calculate the sequence lengths on this subset of data
seq_len = tmp_df.groupby(id_column)[ts_column].count()
# Add the histogram
data.append(
go.Histogram(
x=seq_len,
y=seq_len.index,
histnorm='percent',
name=f'{selected_feat} = {val}'
)
)
layout = go.Layout(
title_text='Sequence length distribution',
xaxis_title_text='Sequence length',
yaxis_title_text='Percent',
paper_bgcolor=layouts.colors['gray_background'],
plot_bgcolor=layouts.colors['gray_background'],
margin=dict(l=0, r=0, t=50, b=0, pad=0),
font=dict(
family='Roboto',
size=font_size,
color=layouts.colors['header_font_color']
)
)
# Get the histogram plot
fig = go.Figure(data, layout)
# Get the list of columns without the identifier and the feature importance columns
shap_column_names = [feature for feature in df.columns
if feature.endswith('_shap')]
feature_names = [feature.split('_shap')[0] for feature in shap_column_names]
# Create the feature dropdown filter
options = list()
options.append(dict(label='All', value='All'))
[options.append(dict(label=feat, value=feat)) for feat in feature_names]
# Create the card
seq_len_dist_card = dbc.Card([
dbc.CardBody([
dcc.Dropdown(
id='seq_len_dist_dropdown',
options=options,
placeholder='Choose a column to filter on',
searchable=True,
persistence=True,
persistence_type='session',
style=dict(
color=layouts.colors['gray_background'],
backgroundColor=layouts.colors['gray_background'],
textColor='white',
fontColor='white'
)
),
dcc.Graph(
figure=fig,
config=dict(
displayModeBar=False
),
style=dict(
height='20em'
)
)
])
], style=style)
return seq_len_dist_card
def create_time_freq_hist_card(df, id_column, ts_column, selected_feat='All', card_height=None, card_width=None, font_size=20):
style = dict()
if card_height is not None:
style['height'] = card_height
if card_width is not None:
style['width'] = card_width
if selected_feat == 'All' or selected_feat == None:
# Calculate the time variation between samples
time_var = df.groupby(id_column)[ts_column].diff()
# Configure the plot
data = [
go.Histogram(
x=time_var,
y=time_var.index,
name='All'
)
]
layout = go.Layout(
title_text='Time variation distribution',
xaxis_title_text='Time difference between samples',
yaxis_title_text='Count',
paper_bgcolor=layouts.colors['gray_background'],
plot_bgcolor=layouts.colors['gray_background'],
margin=dict(l=0, r=0, t=50, b=0, pad=0),
font=dict(
family='Roboto',
size=font_size,
color=layouts.colors['header_font_color']
)
)
else:
# Find the unique values of a column
unique_vals = df[selected_feat].unique()
# Create an histogram for each segment of data that matches each unique value
data = list()
for val in unique_vals:
# Get the data that has the current value
tmp_df = df[df[selected_feat] == val]
# Calculate the time variation between samples
time_var = tmp_df.groupby(id_column)[ts_column].diff()
# Add the histogram
data.append(
go.Histogram(
x=time_var,