-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstats_fun.py
1785 lines (1516 loc) · 77 KB
/
stats_fun.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 os
#os.environ['SF_BACKEND'] = 'tensorflow'
import multiprocessing
import slideflow as sf
import logging
import numpy as np
import pandas as pd
import pprint
import re
import itertools
import json
import csv
import tempfile
import pyarrow
from tabulate import tabulate
from sklearn import metrics
from sklearn.metrics import confusion_matrix
########## Sara's Simplified Slideflow Stats
# ============================================================================ #
######## --------- UTILITY FUNCTIONS ----------- #########
def to_onehot(val, max):
"""Converts value to one-hot encoding.
Args:
val (int): Value to encode
max (int): Maximum value (length of onehot encoding)
"""
onehot = np.zeros(max, dtype=np.int64)
onehot[val] = 1
return onehot
def one_hot(array):
'''Convert arrays with multiple unique values to one-hot binary encoding,
with columns equal to number of unique values.'''
unique, inverse = np.unique(array, return_inverse=True)
onehot = np.eye(unique.shape[0])[inverse]
return onehot
def merge_dict(dict1, dict2):
for key, val in dict1.items():
if type(val) == dict:
if key in dict2 and type(dict2[key] == dict):
merge_dict(dict1[key], dict2[key])
else:
if key in dict2:
dict1[key] = dict2[key]
for key, val in dict2.items():
if not key in dict1:
dict1[key] = val
return dict1
def merge_two_dicts(dict1, dict2):
for key, val in dict1.items():
if type(val) == dict:
if key in dict2 and type(dict2[key] == dict):
merge_dict(dict1[key], dict2[key])
else:
if key in dict2:
dict1[key] = dict2[key]
for key, val in dict2.items():
if not key in dict1:
dict1[key] = val
return dict1
def merge_dict_list(dict_list):
merged_dict = {}
for i in range(len(dict_list)):
dict_to_merge = dict_list[i]
if i == 0:
merged_dict = dict_to_merge
else:
merged_dict = merge_two_dicts(merged_dict, dict_to_merge)
return merged_dict
def flatten(t):
'''Flatten list.'''
return [item for sublist in t for item in sublist]
def find_max_epoch(model_dir):
'''Given a model directory, find the maximum epoch trained to for that model.
Useful when the model & its results saved at multiple epochs.
Args:
model_dir (str): Path to model directory.
Returns:
(int): Maximum epoch trained to.
'''
epoch_list = [re.findall(r'(?<=epoch)\d(?=.\w+)', f) for f in os.listdir(model_dir) if re.findall(r'(?<=epoch)\d(?=.\w+)', f)]
# return the max epoch for a given model directory, theoretically the best epoch
return max(list(set(flatten(epoch_list))))
def get_params(model_dir, keys_list):
# TODO: put in optional keys list from params.json
'''Utility function to pull out desired values from params.json file, given a list of
Args:
model_dir (str): Path to model directory with params.json. Must end with a "/".
keys_list (list): List of param names to use as keys to access values in params.json.
Returns:
params_dict (dict): Dictionary with returned params, keys are from keys_list and
values are extracted from params.json.
'''
f = open(os.path.join(model_dir,"params.json"))
params = json.load(f)
# create dict to return from keys
params_dict = dict.fromkeys(keys_list)
# pull out items from imported json dict
for key in keys_list:
params_dict[key] = params[key]
f.close()
return params_dict
# ============================================================================ #
########### ---- FILE ACCESS FUNCTIONS ------ ###########
def combine_pred_csvs(model_paths, save_path=None):
'''For bootstrapping/crossval purposes, will load in multiple prediction csvs and combine them
if save_path is provided, will save newly created aggregated CSV to desired location.
Args:
models_paths (list): Paths to prediction CSVs to combine. Should all be of same level.
save_path (str, Optional): Path where to save combined prediction CSV.
Returns:
preds_all (DataFrane): Combined predictions.
'''
preds_all = []
for name in model_paths:
try:
preds = pd.read_csv(name)
except UnicodeDecodeError:
preds = pd.read_parquet(name)
preds_all.append(preds)
preds_all = pd.concat(preds_all)
if save_path is not None:
preds_all.to_csv(save_path)
return preds_all
def get_model_names(models_dir, model_label, printplz=False):
# TODO: crosscheck with get_model_paths below
'''Get the list of model paths given a model_label.
Args:
models_dir (str): Path to project models directory.
model_label (str): Label matching model group (bootstrapped/crossvalidated experiment)
printplz (bool): Default False. If True, prints the model names.
Returns:
models_path_list (list): list of model paths.
'''
models_path_list = [models_dir + f for f in os.listdir(models_dir) if re.search(rf'{model_label}', f)]
# print the pred_paths to the console
if printplz is True:
print(models_path_list)
return models_path_list
# def get_model_paths(models_dir, model_patterns):
# # this function is meant to pull out paths of desired models
# list_of_models = []
# for i in model_patterns:
# pattern = i
# list_of_models += [f for f in os.listdir(models_dir) if re.match(rf'{i}', f)]
def get_pred_paths(model_dir, level, epoch=None):
'''Use to get list of prediction CSV filepaths for a given model directory, level, and epoch.
Args:
model_dir (str): Path to model directory that contains prediction files.
level (str): Patient, slide, tile level you want to return prediction file for.
epoch (int): Epoch for whcih to return prediction file for. Default None, will return single epochs.
Returns:
pred_path_list (list): List of prediction file paths for specific level and epoch.
'''
# TODO: change to if epoch
# get list of desired model paths from kfold run and return list of prediction files
pred_path_list = []
# find all prediction CSVs
path_list = [f for f in os.listdir(model_dir) if re.match(r'^.*predictions.*$', f)]
# filter for tile, slide, or patient
path_list = [f for f in path_list if re.match(rf'^{level}.*$', f)]
# filter by specific epoch if epoch is given (if there are multiple), else should just be one, return that for each model
if epoch is not None:
pred_path_list += [model_dir + "/" + f for f in path_list if re.match(rf'^.*epoch{epoch}.*$', f)]
else:
pred_path_list += [model_dir + "/" + f for f in path_list if re.match(rf'^.*epoch.*$', f)]
# return list of what should be three
return pred_path_list
def find_unique_models(models_dir):
'''Given a models_dir, find all unique experiments run; aka return all unique model group labels.
Args:
models_dir (str): Path to project's models directory.
Returns:
unique_runs (list): Labels correspondong to unique model group labels.
'''
model_names = os.listdir(models_dir)
model_groups = [re.split("-kfold\d", re.split("\d{5}-", name)[1])[0] for name in model_names]
unique_runs = list(set(model_groups))
return unique_runs
# ============================================================================ #
###### --------- GET METRICS FUNCTIONS -------- ####
def return_pred_objects(pred_csv_path, level='tile'):
# TODO: extract level from pred_csv_path
'''For a given prediction CSV path, reads in the prediction file and finds objects required for calculating
metrics.
Args:
pred_csv_path_list (list): List of paths to prediction CSV files. All CSVs should from the same k-fold
cross-validated experiment (a model group).
level (str): results level corresponding to CSVs (tile, slide, patient)
Returns:
num_cat (int): Number of outcome categories.
pred_cols (list): List of prediction column names from prediction file..
Example: [Subgroup-y_pred0, Subgroup-y_pred1, Subgroup-y_pred2]
y_pred (ndarray): Softmax prediction values. Each array length equal to number of unique outcome values.
Number of rows is equivalent to number of prediction objects at that level.
Example: array([[1.4923677e-02, 7.2541076e-01, 2.5966552e-01], ...,
[7.5657427e-01, 2.8979644e-02, 2.1444611e-01]], dtype=float32)
true_cols (list): List of true columns names from prediction file.
Example: ['Subgroup-y_true']
y_true (ndarray): Onehot prediction values. Each array length equal to number of unique outcome values.
Number of rows is equivalent to number of prediction objects at that level.
Example: array([[0., 0., 1.], ..., [0., 0., 1.]])
cases (list): Patient IDs corresponding to each line in predictions file.
onehot_predictions (ndarray): predictions but as one-hot encodings instead of softmax.
Example: array([[0, 1, 0], [0, 1, 0], [1, 0, 0],...])
'''
# load in pred CSV as pandas dataframe
try:
preds = pd.read_csv(pred_csv_path)
except UnicodeDecodeError:
preds = pd.read_parquet(pred_csv_path)
# patient/slide vs. tile level
label = 'y_pred' if 'percent_tiles_positive' not in [col for col in preds.columns] else 'percent_tiles_positive'
# pred columns
pred_cols = [col for col in preds.columns if label in col]
y_pred = np.array(preds.loc[:,pred_cols])
# number of categories
num_cat = len(pred_cols)
# true columns
if re.match(rf'.*.csv', pred_csv_path):
true_cols = [col for col in preds.columns if 'y_true' in col]
y_true = np.array(preds.loc[:,true_cols])
#y_true = np.array([to_onehot(i, num_cat) for i in y_true])
else:
true_cols = [col for col in preds.columns if 'y_true' in col]
y_true = np.array(preds.loc[:,true_cols])
y_true = one_hot(y_true.transpose()[0])
# make sure that y_true has the same number of columns as y_pred
if y_true.shape[1] != num_cat:
y_true = np.concatenate((y_true, np.zeros((y_true.shape[0], num_cat - y_true.shape[1]))), axis=1)
# get patient list
if level == 'patient':
cases = list(preds['patient'])
else:
cases = list(preds['slide'])
# one-hot predictions
onehot_predictions = np.array([to_onehot(x, num_cat) for x in np.argmax(y_pred, axis=1)])
#print(onehot_predictions)
return num_cat, pred_cols, y_pred, true_cols, y_true, cases, onehot_predictions
def basic_metrics(y_true, onehot_predictions):
'''Generates basic performance metrics, including sensitivity, specificity, and accuracy. Must be onehot_predictions.
Only for single outcome, so y_pred and y_true from return_pred_objects should be sliced for single outcome.
Args:
y_true (ndarray): Onehot prediction values for single outcome value. Array length equal to number of
prediction objects at that level.
Example: array([0., 0., 1., 0., 1.])
onehot_predictions (ndarray): One-hot encoded predictions for single outcome value. Array length equal to number of
prediction objects at that level.
Example: array([0, 0, 1, 0, 1])
Returns:
metrics_dict (dict): dictionary of calculated metric values.
Example: {'accuracy': 0.33,
'sensitivity': 0.0,
'specificity': 0.5,
'precision': 0.0,
'recall': 0.0,
'f1_score': 0.0,
'kappa': -0.5}
'''
#print(y_true)
assert(len(y_true) == len(onehot_predictions))
assert([y in [0,1] for y in y_true])
assert([y in [0,1] for y in onehot_predictions])
TP = 0 # True positive
TN = 0 # True negative
FP = 0 # False positive
FN = 0 # False negative
for i, yt in enumerate(y_true):
yp = onehot_predictions[i]
if yt == 1 and yp == 1:
TP += 1
elif yt == 1 and yp == 0:
FN += 1
elif yt == 0 and yp == 1:
FP += 1
elif yt == 0 and yp == 0:
TN += 1
addtl_metrics = ['accuracy', 'sensitivity', 'specificity', 'precision', 'recall', 'f1_score', 'kappa']
metrics_dict = {key: {} for key in addtl_metrics}
try:
metrics_dict['accuracy'] = round((TP + TN) / (TP + TN + FP + FN), 2)
except ZeroDivisionError:
metrics_dict['accuracy'] = np.nan
try:
metrics_dict['sensitivity'] = round(TP / (TP + FN), 2)
except ZeroDivisionError:
metrics_dict['sensitivity'] = np.nan
try:
metrics_dict['specificity'] = round(TN / (TN + FP), 2)
except ZeroDivisionError:
metrics_dict['specificity'] = np.nan
metrics_dict['precision'] = round(metrics.precision_score(y_true, onehot_predictions, zero_division=0), 2)
metrics_dict['recall'] = round(metrics.recall_score(y_true, onehot_predictions), 2)
metrics_dict['f1_score'] = round(metrics.f1_score(y_true, onehot_predictions), 2)
metrics_dict['kappa'] = round(metrics.cohen_kappa_score(y_true, onehot_predictions), 2)
return metrics_dict
def get_aucs(y_true, y_pred):
'''Generate AUROC and AUPRC from outcome probabilities (continuous, not onehot). Only for single outcome,
so y_pred and y_true from return_pred_objects should be sliced for single outcome.
Args:
y_true (ndarray): Onehot prediction values for single outcome value. Array length equal to number of
prediction objects at that level.
Example: array([0., 0., 1., 0., 1.])
y_pred (ndarray): Softmax prediction values for single outcome value. Array length equal to number of
prediction objects at that level.
Example: array([0, 0, 1, 0, 1])
Returns:
metrics_dict (dict): Dict with keys 'AUROC', 'AUPRC'.
Example: {'AUROC': 0.5, 'AUPRC': 0.5}
'''
assert(len(y_true) == len(y_pred))
auc_metrics = ['AUROC', 'AUPRC']
metrics_dict = {key: {} for key in auc_metrics}
# generate AUROC
fpr, tpr, threshold = metrics.roc_curve(y_true, y_pred)
roc_auc = metrics.auc(fpr, tpr)
# generate AUPRC
auprc = metrics.average_precision_score(y_true, y_pred)
metrics_dict['AUROC'] = round(roc_auc, 2)
metrics_dict['AUPRC'] = round(auprc, 2)
return metrics_dict
def get_metrics_outcome(y_true, y_pred, onehot_predictions, cat_num):
'''Get all metrics for a single outcome value and return dictionary of metrics.
Args:
y_true (ndarray): Onehot prediction values for single outcome value. Array length equal to number of
prediction objects at that level.
Example: array([0., 0., 1., 0., 1.])
y_pred (ndarray): Softmax prediction values for single outcome value. Array length equal to number of
prediction objects at that level.
Example: array([1.4923677e-02, 2.1980377e-05, 9.9800617e-01, 5.6900114e-02, 7.5657427e-01], dtype=float32)
onehot_predictions (ndarray): One-hot encoded predictions for single outcome value. Array length equal to number of
prediction objects at that level.
Example: array([0, 0, 1, 0, 1])
cat_num (int): Integer outcome value metrics are being generated for.
Returns:
cat_dict (dict): Dict of metrics returned for particular outcome value (key), values are metrics.
Example: {0: {'accuracy': 0.77,
'sensitivity': 0.72,
'specificity': 0.79,
'precision': 0.63,
'recall': 0.72,
'f1_score': 0.67,
'kappa': 0.5,
'AUROC': 0.8,
'AUPRC': 0.7,
'ConfusionMatrix': array([[44786, 11612],
[ 7806, 20084]])}}
'''
cat_dict = {}
basic_metrics_dict = basic_metrics(y_true, onehot_predictions)
aucs_dict = get_aucs(y_true, y_pred)
cm_dict = get_confusion_matrix(y_true, onehot_predictions)
cat_dict[cat_num] = merge_dict_list([basic_metrics_dict, aucs_dict, cm_dict])
return cat_dict
def gen_metrics_all_outcomes(num_cat, y_pred, y_true, onehot_predictions):
'''Generate metrics for all categories and returned combined dictionary. Metrics will be generated for
all outcome vategories.
Args:
num_cat (int): Number of outcome categories.
y_pred (ndarray): Softmax prediction values. Each array length equal to number of unique outcome values.
Number of rows is equivalent to number of prediction objects at that level.
Example: array([[1.4923677e-02, 7.2541076e-01, 2.5966552e-01], ...,
[7.5657427e-01, 2.8979644e-02, 2.1444611e-01]], dtype=float32)
y_true (ndarray): Onehot prediction values. Each array length equal to number of unique outcome values.
Number of rows is equivalent to number of prediction objects at that level.
Example: array([[0., 0., 1.], ..., [0., 0., 1.]])
onehot_predictions (ndarray): predictions but as one-hot encodings instead of softmax.
Example: array([[0, 1, 0], [0, 1, 0], [1, 0, 0],...])
Returns:
merged_cat_dict (dict): Dict of metrics for model, keys are integer outcome values.
Example: {0: {'accuracy': 0.77,
'sensitivity': 0.72,
'specificity': 0.79,
'precision': 0.63,
'recall': 0.72,
'f1_score': 0.67,
'kappa': 0.5,
'AUROC': 0.8,
'AUPRC': 0.7,
'ConfusionMatrix': array([[44786, 11612],
[ 7806, 20084]])},
1: {'accuracy': 0.84, ...},
2: {'accuracy': 0.84, ...}}
'''
cat_dict_list = []
for i in range(num_cat):
cat_dict_list += [get_metrics_outcome(y_true[:,i], y_pred[:,i], onehot_predictions[:,i], i)]
merged_cat_dict = merge_dict_list(cat_dict_list)
return merged_cat_dict
def get_metrics_from_pred(pred_csv_path, level):
'''Generate merged metrics dictionary for all outcomes for a certain level.
Args:
pred_csv_path (list): Path to prediction CSV file.
level (str): results level corresponding to CSVs (tile, slide, patient)
Returns:
merged_metrics_dict (dict): Dict of metrics for model, keys are integer outcome values.
Example: Same return as above gen_metrics_all_outcomes.
'''
num_cat, pred_cols, y_pred, true_cols, y_true, cases, onehot_predictions = return_pred_objects(pred_csv_path, level=level)
merged_metrics_dict = gen_metrics_all_outcomes(num_cat, y_pred, y_true, onehot_predictions)
return merged_metrics_dict
# ============================================================================ #
######### --------- CONFUSION MATRICES ----------- ##########
def get_confusion_matrix(y_true, onehot_predictions, labels=False):
'''Generate 2x2 Confusion Matrix from onehot predictions for a single outcome value (not multicategorical/multilabel).
To get multicategorical/multilabel CM, use aggregated_confmat() below.
Simplest function, will just get you a single, pretty confusion matrix.
Returns as a dict to make it easy to combine with metrics dictionary.'''
cm_obj = metrics.confusion_matrix(y_true, onehot_predictions)
if labels is True:
cm_obj = pretty_confusionmatrix(cm_obj)
return {"ConfusionMatrix": cm_obj}
def pretty_confusionmatrix(cm_obj):
# TODO: adjust for other options
# input CM should have format like: [[1 2], [0 3]], this assigns proper labels to it
cmtx = pd.DataFrame(cm_obj, index=['true:yes', 'true:no'], columns=['pred:yes', 'pred:no'])
#cmtx.style.set_table_styles([dict(selector='th', props=[('text-align', 'center')])])
return cmtx
def aggregated_confmat(pred_csv_path_list, title=None, format="plot", save_path=None, **kwargs):
# TODO: in theory, i could remove the level arg and get that from the pred_csv_path_list instead
"""Produce an aggregated Confusion Matrix that is N x N where N is the number of unique outcome values, as
well as a list of N length containing 2x2 CMs corresponding to each outcome. Also can plot & save plot.
Args:
pred_csv_path_list (list): List of paths to prediction CSV files. All CSVs should from the same k-fold
cross-validated experiment (a model group).
#level (str): results level corresponding to CSVs (tile, slide, patient)
title (str): Title of plot.
format (str): Format of output. Options are "plot", "2x2" or "NxN". If "plot", will plot the confusion matrix.
save_path (str): Path where to save the confusion matrix.
**kwargs: Additional arguments to pass to the ConfusionMatrixDisplay.from_predictions() function.
Returns:
cm2 (NumPy array): An N X N NumPy array where N is the number of unique outcome values, the y axis is the
True labels and the x axis is the false.
mlb_cm (list of arrays): Returns a list of 2x2 CMs
The function will also plot the confusion matrix as well
# TODO: THOUGH... this could use some actual labels
Example:
NxN format, cm2:
[[4 1 0 0 0 0 0 0]
[2 0 3 1 0 0 0 0]
[0 0 5 0 0 0 0 0]
[0 0 2 6 0 0 0 0]
[0 0 2 2 2 0 0 0]]
2x2 format, mlb_cm:
[[[29 3] [[30 1] [[25 7] [[23 6] [[31 0]
[ 1 4]] [ 6 0]] [ 0 5]] [ 2 6]] [ 4 2]]]
"""
if type(pred_csv_path_list) is list:
# combine all the prediction files into one large file
aggregated_pred_csv = combine_pred_csvs(pred_csv_path_list)
# save temp file to use
with tempfile.NamedTemporaryFile(mode='w', delete=False) as csvfile:
aggregated_pred_csv.to_csv(csvfile)
pred_csv_path = csvfile.name
# level
level = pred_csv_path_list[0].split("/")[-1].split("_")[0]
else:
pred_csv_path = pred_csv_path_list
level = pred_csv_path.split("/")[-1].split("_")[0]
_, _, _, _, y_true, _, onehot_predictions = return_pred_objects(pred_csv_path, level)
class_pred = np.argmax(onehot_predictions, axis=1) # reversing onehot encoding https://www.codegrepper.com/code-examples/python/reverse+one+hot+encoding+python+numpy
class_true = np.argmax(y_true, axis=1)
# if pred_csv_path_list is a temp file, use pred_csv_path_list[0] to get the path to the first file
# use regex expression to identify if the path is a temp file or not
if re.search(r'tmp', pred_csv_path):
oc_lbls = get_params(pred_csv_path_list[0].split(level)[0], ["outcome_labels"])['outcome_labels']
else:
oc_lbls = get_params(pred_csv_path.split(level)[0], ["outcome_labels"])['outcome_labels']
from sklearn.metrics import confusion_matrix, multilabel_confusion_matrix, ConfusionMatrixDisplay
# cm is a normal confusion matrix
if format == "2x2":
cm2 = confusion_matrix(class_true,class_pred)
return cm2
# multilabel confusion matrix returns a list of 2x2 CMs, one CM for each unique outcome
if format == "NxN":
mlb_cm = multilabel_confusion_matrix(y_true, onehot_predictions)
return mlb_cm
# plotting
if format == "plot":
disp = ConfusionMatrixDisplay.from_predictions(class_true, class_pred, display_labels=list(oc_lbls.values()), xticks_rotation='vertical', **kwargs)
#disp.ax_.set_title(title)
# import matplotlib.pyplot as plt
# plt.show()
# if save_path:
# disp.figure_.savefig(save_path, bbox_inches='tight')
return disp
#def get_usable_dicts()
# ============================================================================ #
######## --------- SLIDE MANIFEST NUMBERS ----------- ##########
def get_sm_paths(model_dirs):
'''Takes a list of paths to each model directories and returns list of paths to slide manifests in each directory.'''
# return list of slide manifest paths
return [os.path.join(model_dir,"slide_manifest.csv") for model_dir in model_dirs]
def get_manifest_numbers(sm_path):
# TODO: Could add option to label unique outcomes using a column for the outcomes.
'''Takes path to slide manifest file as argument. Will return slide manifest numbers for training model OR for
training model used for evaluation (if SM path is an evaluation directory).
Returns a dataframe with columns "train", "val", "total" with rows
as each unique outcome value. Row index corresponds to each unique outcome value.
train val total
0 9 3 12
1 14 1 15
2 21 8 29
'''
# get slide manifest numbers for an individual model
sm = pd.read_csv(sm_path)
# get numbers
if "-eval-" in sm_path:
# get numbers for training from training model directory
train_sm_path = get_params(sm_path.split("slide_manifest.csv")[0], ["model_path"])['model_path'] + "/slide_manifest.csv"
train_sm = pd.read_csv(train_sm_path)
sm_nums = pd.concat([train_sm[train_sm['dataset']=="training"]["outcome_label"].value_counts(), sm[sm['dataset']=="validation"]["outcome_label"].value_counts()], axis=1).sort_index()
sm_nums.columns = ["train", "val"]
sm_nums['total'] = sm_nums.train + sm_nums.val
else:
# get numbers for
sm_nums = pd.concat([sm[sm['dataset']=="training"]["outcome_label"].value_counts(), sm[sm['dataset']=="validation"]["outcome_label"].value_counts(), sm["outcome_label"].value_counts()], axis=1).sort_index()
sm_nums.columns = ["train", "val", "total"]
# apply int to dataframe sm_nums and also coerce NaNs to 0
sm_nums = sm_nums.apply(pd.to_numeric, errors='coerce').fillna(0).astype(int)
return sm_nums
def get_manifest_numbers_mg(sm_path_list):
# TODO: maybe combine this with get_manifest_numbers() and add an argument to specify if it's a model group or not
'''Takes a list of paths to slide manifests, which should each be from a kfold from a cross-validation experiment.
Will return a dictionary with keys corresponding to each kfold number and the values as the SM dataframe returned from
get_manifest_numbers().
Returns: Dictionary like below:
{'1': train val total
0 9 3 12
1 14 1 15
2 21 8 29,
...
'3': train val total
0 8 4 12
1 11 4 15
2 19 10 29}
'''
# get manifest numbers from each kfold in model group
sm_kfold_dicts = {}
for file in sm_path_list:
# get kfold name
kfold_num = re.findall(r'(?<=kfold)\d', file)[0]
sm_kfold_dicts[kfold_num] = get_manifest_numbers(file)
return sm_kfold_dicts
def avg_sm_split(sm_kfold_dicts):
'''From slide manifest train/val number dictionaries pulled from each kfold, get avg & summarize.
Args:
sm_kfold_dicts (dict): Dict of DataFrames containing train, val, totals for each outcome, keys are kfold num.
Example: sm_kfold_dicts = get_manifest_numbers_mg(sm_paths)
Returns: Dataframe like below with addtl total col (below is tabulate printed)
train val total
-- ------------------- ------------------ -------
0 8 (8/9/8/8/9) 4 (4/3/4/4/3) 12
1 12 (13/12/12/11/14) 3 (2/3/3/4/1) 15
2 21 (20/24/21/19/21) 8 (9/5/8/10/8) 29
Example:
df = avg_sm_split(sm_kfold_dicts)
from tabulate import tabulate
print(tabulate(df, showindex=True, headers=df.columns, ))
'''
# get keys (kfolds) and put them in ascending order
kfolds = list(sm_kfold_dicts.keys())
kfolds.sort()
# get training values
train_vals = pd.concat([sm_kfold_dicts[i]['train'] for i in kfolds], axis=1)
train_vals.columns = kfolds
# find average
train_vals['average'] = round(train_vals.mean(axis=1)).astype(int)
# convert all to str
train_vals = train_vals.applymap(str)
# join entire thing into string with averages
train_nums = train_vals['average'] + " (" + train_vals[kfolds].stack().groupby(level=0).apply('/'.join) + ")"
# get validation values
val_vals = pd.concat([sm_kfold_dicts[i]['val'] for i in kfolds], axis=1)
val_vals.columns = kfolds
# find average
val_vals['average'] = round(val_vals.mean(axis=1)).astype(int)
# convert all to str
val_vals = val_vals.applymap(str)
# join entire thing into string with averages
val_nums = val_vals['average'] + " (" + val_vals[kfolds].stack().groupby(level=0).apply('/'.join) + ")"
# add up totals from avgs into new column "total"
total_nums = train_vals['average'].astype(int) + val_vals['average'].astype(int)
# get total train/validation numbers
train_total = sum(train_vals['average'].astype(int))
val_total = sum(val_vals['average'].astype(int))
# concat into one df
sm_nums = pd.concat([train_nums, val_nums, total_nums], axis=1).sort_index()
sm_nums.columns = ["train","val","total"]
return sm_nums, train_total, val_total
def get_sm_stats(model_dirs, label_outcomes=False):
'''From model group model directories, get slide manifest paths, pull out slide manifests
from each kfold, then find train/val numbers and averages for each kfold.
If label_outcomes is True, dataframe index will be labeled with outcome values.
Args:
models_dirs (list): List to model directories for model group (typically crossvalidated experiment)
label_outcomes (bool): Default False. Determines if returned sm_stats should be labeled with outcomes.
Returns:
Tuple consisting of dataframe with columns for train, val, and total, where entries for train & val
contain the averaged number across all k-folds and then the individual k-fold numbers. 2nd and 3rd
tuple entries are total numbers for training & validation.
Example:
( train val total
outcome
ERMS 8 (8/9/8/8/9) 4 (4/3/4/4/3) 12
HGESS 12 (13/12/12/11/14) 3 (2/3/3/4/1) 15
...
PEComa 12 (13/13/12/11/13) 4 (3/3/4/5/3) 16
UTROSCT 9 (9/10/10/8/9) 3 (3/2/2/4/3) 12, 122, 43)
'''
# get sm paths
sm_path_list = get_sm_paths(model_dirs)
# get sm numbers for each kfold
sm_kfold_dicts = get_manifest_numbers_mg(sm_path_list)
# find averages and concatenate numbers to return train/val numbers dataframe
sm_stats, train_total, val_total = avg_sm_split(sm_kfold_dicts)
# add totals as last row
sm_stats = pd.concat([sm_stats, pd.DataFrame([int(train_total), int(val_total), int(train_total+val_total)],
index=['train', 'val', 'total']).T], axis=0)
# label with outcome labels if desired
if label_outcomes is True:
oc_lbls = get_params(model_dirs[0], ["outcome_labels"])['outcome_labels']
oc_lbl_df = pd.DataFrame.from_dict(oc_lbls, orient='index', columns=['outcome'])
oc_lbl_df.loc[len(oc_lbl_df.index)] = ['total']
# concat oc_lbl_df to sm_stats reset index
sm_stats = pd.concat([oc_lbl_df.reset_index(drop=True), sm_stats.reset_index(drop=True)], axis=1)
return sm_stats
# ============================================================================
# MODEL GROUP & KFOLD FUNCTIONS FOR AGGREGATING METRICS
def find_results_kfolds(pred_csv_path_list, level):
# TODO: may want to combine this function with the below as they both pretty much do the same thing.
# I can also see it being prudent to just make everything numpy arrays
'''Find metrics for all models (should be kfolds from crossval experiment).
Return a single dict with kfold numbers as keys and results as values.
Args:
pred_csv_path_list (list): List of paths to prediction CSVs.
level (str): Prediction level (patient, slide, tile).
Returns:
kfold_dicts (dict): Dict with kfolds as str keys, values are nested dicts of metric
results for each outcome value, where those keys are int.
Example: See below find_crossval_plus_avg_results, but this one only returns individuak kfold results.
'''
kfold_dicts = {}
for file in pred_csv_path_list:
# get kfold name
kfold_num = re.findall(r'(?<=kfold)\d', file)[0]
kfold_dicts[kfold_num] = get_metrics_from_pred(file, level=level)
return kfold_dicts
def get_avg_crossval_results(pred_csv_path_list, level):
# TODO: may want to combine this function with the below as they both pretty much do the same thing.
'''Aggregate results from different kfolds into one CSV file and then find metrics for each outcome over
kfolds/models provided in pred_csv_path_list. Basically averaged crossval performance.
Default metrics are : accuracy, sensitivity, specificity, recall, f1_score, kappa, AUROC, AUPRC, ConfusionMatrix
Args:
pred_csv_path_list (list): List of paths to prediction CSVs.
level (str): Prediction level (patient, slide, tile).
Returns:
aggregated_crossval_metrics_dict (dict): Nested dict like below where second level nest is the integer
outcome values as keys and values are the averaged metrics.
Example: See below find_crossval_plus_avg_results, but this one only returns averaged results.
'''
# aggregate results from different kfolds into one CSV file and then find metrics (basically averaged crossval performance)
aggregated_pred_csv = combine_pred_csvs(pred_csv_path_list)
# save temp file to use
with tempfile.NamedTemporaryFile(mode='w', delete=False) as csvfile:
aggregated_pred_csv.to_csv(csvfile)
aggregated_crossval_metrics_dict = {}
# get path of temp csv file using .name attribute & use to get metrics
aggregated_crossval_metrics_dict["average"] = get_metrics_from_pred(csvfile.name, level=level)
return aggregated_crossval_metrics_dict
def find_crossval_plus_avg_results(pred_csv_path_list, level):
'''Essentially combines crossvalidated kfold results (from find_results_kfolds) plus averaged results
over kfolds (get_avg_crossval_results) into one dictionary.
Alternative is get_avg_results, which returns a DataFrame.
Args:
pred_csv_path_list (list): List of paths to prediction CSVs.
level (str): Prediction level (patient, slide, tile).
Returns:
crossval_dict (dict): Nested dict like below where second level nest is the integer outcome values
as keys and values are the averaged metrics. Kfolds as str keys, values are nested dicts of metric
results for each outcome value, where those keys are int.
Example:
{'average': {0: {'accuracy': 0.72,
'sensitivity': 0.54,
'specificity': 0.81,
'precision': 0.61,
'recall': 0.54,
'f1_score': 0.57,
'kappa': 0.36,
'AUROC': 0.75,
'AUPRC': 0.59,
'ConfusionMatrix': array([[132489, 30827],
[ 40379, 47313]])},
1: {...},
2: {...}},
'3': {0: {'accuracy': 0.88, ...}
1: {...},
2: {...}},
'2': {0: {'accuracy': 0.90, ...}
1: {...},
2: {...}},
'1': {0: {'accuracy': 0.69, ...}
1: {...},
2: {...}}}
'''
# find both kfold & aggregated dicts and combine into one big dictionary
kfold_dicts = find_results_kfolds(pred_csv_path_list, level)
aggregated_crossval_metrics_dict = get_avg_crossval_results(pred_csv_path_list, level)
crossval_dict = merge_two_dicts(kfold_dicts, aggregated_crossval_metrics_dict)
return crossval_dict
def concat_results_df(kfold_dict, average_dict, metric_list=["AUROC","AUPRC","accuracy","precision","recall",
"sensitivity","specificity","ConfusionMatrix"], outcome_labels=None):
''' Find concatenated results dataframe of summarized averaged + kfold results and averaged results.
Likely redundant with get_avg_results() below but this one is from the dictionary values.
Args:
kfold_dict (dict): Dict of kfold results from find_results_kfolds()
average_dict (dict): Dict of averaged kfold results from get_avg_crossval_results().
metric_list (list): Metrics you want to see summarized.
outcome_labels (dict): Expects to be dictionary of numeric values mapping to outcome labels.
Returns:
result_df (DataFrame): Outcomes (rows) and metrics (cols) with each cell being the averaged value and
then the k-fold values in parentheses.
Example:
AUROC AUPRC ConfusionMatrix
0 0.75 (0.8/0.74/0.74) 0.59 (0.7/0.5/0.6) [[132489 30827] [ 40379 47313]] ([[44786 1...
1 0.9 (0.9/0.94/0.85) 0.78 (0.77/0.84/0.73) [[170750 18908] [ 19058 42292]] ([[56871 ...
2 0.72 (0.74/0.7/0.74) 0.64 (0.61/0.67/0.67) [[102819 46223] [ 36521 65445]] ([[37657 1..
avg_df (DataFrame): Outcomes (rows) and metrics (cols) as averaged results across kfolds from kfold_dict.
Example:
AUROC AUPRC ConfusionMatrix
0 0.75 0.59 [[132489, 30827], [40379, 47313]]
1 0.9 0.78 [[170750, 18908], [19058, 42292]]
2 0.72 0.64 [[102819, 46223], [36521, 65445]]
'''
# TODO make option to just summarize kfolds vs. averaged dictionary as well
# convert kfold_dict to DataFrame
df_list = [pd.DataFrame.from_records(kfold_dict[i]).T for i in list(kfold_dict.keys())]
# example of what df_list looks like
# temp = pd.DataFrame.from_records(m_dict)
# temp.T
# accuracy sensitivity specificity precision recall f1_score kappa AUROC AUPRC ConfusionMatrix
# 0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 [[10, 0], [0, 25]]
# 1 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 [[25, 0], [0, 10]]
# average df only
avg_df = pd.DataFrame.from_records(average_dict["average"]).T
avg_df = avg_df[metric_list]
# assume 3 kfolds
# https://stackoverflow.com/questions/39291499/how-to-concatenate-multiple-column-values-into-a-single-column-in-pandas-datafra
# example = avg_df["AUPRC"].astype(str) + " (" + df_list[0]["AUPRC"].astype(str) + "/" + df_list[1]["AUPRC"].astype(str) + "/" + df_list[2]["AUPRC"].astype(str) + ")"
newcol_list = []
for metric_name in metric_list:
kfoldslist = avg_df[metric_name].astype(str) + " ("
for i in range(len(df_list)):
if i != (len(df_list)-1):
kfoldslist = kfoldslist + df_list[i][metric_name].astype(str) + "/"
else:
kfoldslist = kfoldslist + df_list[i][metric_name].astype(str) + ")"
newcol_list += [kfoldslist]
# concat columns back into one another
result_df = pd.concat(newcol_list, axis=1)
# get outcome labels & use them to set index of result_df
if outcome_labels is not None:
# convert integer string to just int to allow for labeling on index
outcome_labels = {int(k):v for k,v in outcome_labels.items()}
oc_lbl_df = pd.DataFrame.from_dict(outcome_labels, orient='index', columns=['outcome'])
result_df = result_df.set_index(oc_lbl_df['outcome'])
avg_df = avg_df.set_index(oc_lbl_df['outcome'])
return result_df, avg_df
def get_avg_results(models_dir, mg, level, metric_list=["AUROC","AUPRC","accuracy","precision","recall","sensitivity","specificity","ConfusionMatrix"]):
'''For a given model group (a group of models, typically a k-fold cross-validated/bootstrapped experiment)
at a certain desired result level (tile, slide, or patient), this function finds the average performance
across the k-folds for a given list of metrics and for one set of hyperparameters.
Alternative to find_crossval_plus_avg_results, which returns nested dictionaries.
Args:
models_dir (str): Path to project models/ directory.
mg (str): label for specific model group to get averaged results for
Ex: 'dx_short-299_ES_unbalanced_bootstrap-HP0'
level (str): desired results level, either "tile", "slide", or "patient"
metric_list (list): A list of desired metrics. Default are ["AUROC","AUPRC","accuracy","precision",
"recall","sensitivity","specificity","ConfusionMatrix"]
Returns:
avg_df (Dataframe): Columns are metrics in given metric_list, rows are each outcome value,
cells are the average performance across k-folds of the outcome for a given metric. Index is the
labeled outcomes.
Example:
AUROC AUPRC accuracy precision recall sensitivity specificity ConfusionMatrix
outcome
ERMS 0.99 0.91 0.96 0.65 0.79 0.79 0.97 [[185, 6], [3, 11]]
HGESS 0.92 0.59 0.88 0.42 0.48 0.48 0.92 [[170, 14], [11, 10]]
IMT 0.94 0.87 0.92 0.85 0.65 0.65 0.98 [[167, 4], [12, 22]]
'''
# search through model folders in models dir to get desired models from label (outcome-exp_label-HP#)
model_dirs = get_model_names(models_dir, mg)
# use each model_dir to get the desired epoch
epochs = [find_max_epoch(mdl_dir) for mdl_dir in model_dirs]
# cycle through each model dir and epoch
pred_path_list = flatten([get_pred_paths(mdl, level, ep) for mdl,ep in zip(model_dirs,epochs)])
# for this model group, get the results using pred_path_list (which has 3 CSVs for a specific level & epoch)
kfold_dict = find_results_kfolds(pred_path_list, level)
# use kfold dicts to get average
avg_dict = get_avg_crossval_results(pred_path_list, level)
avg_df = pd.DataFrame.from_records(avg_dict['average']).T
# filter for desired metrics
if metric_list is not None:
avg_df = avg_df[metric_list]
oc_lbls = get_params(pred_path_list[0].split(level)[0], ["outcome_labels"])['outcome_labels']
# convert integer string to just int to allow for labeling on index
oc_lbls = {int(k):v for k,v in oc_lbls.items()}
oc_lbl_df = pd.DataFrame.from_dict(oc_lbls, orient='index', columns=['outcome'])
# avg_df = avg_df.set_index(oc_lbl_df['outcome']) # old way, where outcome labels are index values
avg_df = pd.concat([oc_lbl_df, avg_df], axis=1)
return avg_df
def get_eval_results(pred_csv_path, level, metric_list=["AUROC","AUPRC","accuracy","precision","recall","sensitivity","specificity","ConfusionMatrix"]):
'''For a given prediction file from an evaluation model, return the evaluation performance metrics for a
desired results level (tile, slide, patient) as a Pandas Dataframe.
Args:
pred_csv_path (str): Path to prediction file.
level (str): desired results level, either "tile", "slide", or "patient"
metric_list (list): A list of desired metrics. Default are ["AUROC","AUPRC","accuracy","precision",
"recall","sensitivity","specificity","ConfusionMatrix"]
Returns:
eval_df (Pandas Dataframe): Columns are metrics in given metric_list, rows are each outcome value,
cells are the evaluation performance of the outcome for a given metric. Index is the labeled outcomes.
Example:
AUROC AUPRC accuracy sensitivity specificity ConfusionMatrix
outcome
ERMS 0.97 0.86 0.92 0.8 0.94 [[30, 2], [1, 4]]
HGESS 0.65 0.32 0.81 0.0 0.97 [[30, 1], [6, 0]]
IMT 0.98 0.92 0.78 1.0 0.75 [[24, 8], [0, 5]]
'''
# find metrics for evaluation for a specific model
eval_dict = get_metrics_from_pred(pred_csv_path, level)
eval_df = pd.DataFrame.from_records(eval_dict).T
# filter for desired metrics
if metric_list is not None:
eval_df = eval_df[metric_list]
# outcome labels
oc_lbls = get_params(pred_csv_path.split(level)[0], ["outcome_labels"])['outcome_labels']
# convert integer string to just int to allow for labeling on index
oc_lbls = {int(k):v for k,v in oc_lbls.items()}
oc_lbl_df = pd.DataFrame.from_dict(oc_lbls, orient='index', columns=['outcome'])
# eval_df = eval_df.set_index(oc_lbl_df['outcome']) # old way, has outcomes as index and not as a column