-
Notifications
You must be signed in to change notification settings - Fork 0
/
paper_analysis.py
2099 lines (1962 loc) · 80.5 KB
/
paper_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
# imports
import colorsys
import json
import pickle
import re
import sys
from collections import defaultdict
from functools import cache
from pathlib import Path
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import omegaconf
import pandas as pd
import seaborn as sns
from loguru import logger
from matplotlib.markers import MarkerStyle
from utils import load_fd_results_hydra, load_raw_results
from segmentation_failures.evaluation.failure_detection.fd_analysis import (
ExperimentData,
compute_fd_scores,
)
from segmentation_failures.evaluation.segmentation.segmentation_metrics import (
get_metrics_info,
)
from segmentation_failures.utils import GLOBAL_SEEDS
from segmentation_failures.utils.data import get_dataset_dir
dataset_mapper = {
500: "Brain tumor (2D)",
503: "Brain tumor",
514: "Heart (US)",
510: "Heart (ACDC)",
511: "Heart", # M&Ms
515: "Kidney tumor",
520: "Covid",
521: "Prostate",
540: "OCT (fluids)",
560: "OCT (layers)",
531: "Optic cup/disc",
}
pixel_csf_mapper = {
"baseline": "Single network",
"mcdropout": "MC-Dropout",
"deep_ensemble": "Ensemble",
}
image_csf_mapper = {
"quality_regression": "Quality regression",
"mahalanobis_gonzalez": "Mahalanobis",
"vae_mask_only": "VAE (seg)",
"vae_image_and_mask": "VAE (img + seg)",
}
agg_mapper = {
"pairwise_dice": "pairwise DSC",
"pairwise_gen_dice": "pairwise DSC",
"pairwise_mean_dice": "pairwise DSC",
"predictive_entropy_mean": "mean PE",
"predictive_entropy_foreground": "mean foreground PE",
"predictive_entropy_only_non_boundary": "non-boundary PE",
"predictive_entropy_patch_min": "patch-based PE",
"predictive_entropy+heuristic": "RF (simple PE-features)",
"predictive_entropy+radiomics": "RF (radiomics PE-features)",
}
label_mapper = {
"aurc": "AURC ↓",
"norm-aurc": "nAURC ↓",
"eaurc": "eAURC ↓",
"dice": "DSC",
"generalized_dice": "generalized DSC",
"mean_dice": "mean DSC",
"spearman": "SC ↓",
"pearson": "PC ↓",
"ood_auc": "AUROC (ood) ↑",
"mean_surface_dice": "mean NSD",
}
color_palette = [
tuple(int(clr.lstrip("#")[i : i + 2], 16) / 255 for i in (0, 2, 4))
for clr in sns.color_palette("tab10").as_hex()
]
MAIN_SEG_METRIC = "mean_dice"
PAPER_TEXTWIDTH = 7.23135 # inches
PAPER_TEXTHEIGHT = 9.57262 # inches
def get_figsize(textwidth_factor=1.0, aspect_ratio=None):
width = PAPER_TEXTWIDTH * textwidth_factor
if aspect_ratio is None:
aspect_ratio = (np.sqrt(5) - 1.0) / 2.0 # because it looks good
height = width * aspect_ratio # figure height in inches
return width, height
@cache
def get_num_test_cases(dataset_id, root_dir=None):
if root_dir is None:
root_dir = "/home/m167k/Datasets/segmentation_failures/nnunet_convention_new"
# a) count files in the folders <- better
# b) hard-coded here
data_root = get_dataset_dir(dataset_id, root_dir)
return len(list(data_root.glob("labelsTs/*.nii.gz")))
def order_expts(mapped_expt_names, separate_pxl_and_img_csfs=True):
# use the order implied by the mapper dicts.
# First pixel confidence scores (order among them by confid name), then image confidence scores (order among them alphabetically)
def get_order_position(expt_name):
pixel_confid, image_confid = expt_name.split(" + ")
pixel_methods = list(pixel_csf_mapper.values())
img_methods = list(image_csf_mapper.values())
agg_methods = list(agg_mapper.values())
# compute an order score, based on the positions in the mapper dicts
num_per_pixel_confid = len(agg_methods) + len(img_methods)
if image_confid in agg_methods:
order_score = pixel_methods.index(
pixel_confid
) * num_per_pixel_confid + agg_methods.index(image_confid)
else:
order_score = (
+pixel_methods.index(pixel_confid) * num_per_pixel_confid
+ len(agg_methods)
+ img_methods.index(image_confid)
)
if separate_pxl_and_img_csfs:
# they will come after all pixel+aggregation methods
# e.g. single network + mean PE, ensemble + mean PE, single_network + quality regression
order_score += 1000
return order_score
ordered_names = sorted(mapped_expt_names, key=get_order_position)
if len(ordered_names) != len(mapped_expt_names):
raise ValueError(f"Unknown experiment name {set(mapped_expt_names) - set(ordered_names)}")
return ordered_names
def adjust_saturation(rgb, factor):
"""Adjust the saturation of an RGB color."""
hsl = colorsys.rgb_to_hls(*rgb)
hsl_adjusted = (hsl[0], min(max(0, hsl[1] * factor), 1), hsl[2])
return colorsys.hls_to_rgb(*hsl_adjusted)
def save_and_close(
fig: matplotlib.figure.Figure,
output_path: Path,
file_types=None,
fix_axis_labels=True,
**kwargs,
):
if file_types is None:
file_types = [".png", ".pdf"]
if output_path.suffix not in file_types:
file_types.append(output_path.suffix)
default_kwargs = {
"dpi": 200,
"bbox_inches": "tight",
}
default_kwargs.update(kwargs)
if fix_axis_labels:
for ax in fig.get_axes():
if ax.get_xlabel():
ax.set_xlabel(get_nicer_axis_label(ax.get_xlabel()))
if ax.get_ylabel():
ax.set_ylabel(get_nicer_axis_label(ax.get_ylabel()))
for file_type in file_types:
fig.savefig(output_path.with_suffix(file_type), **default_kwargs)
plt.close(fig)
def get_nicer_axis_label(label: str):
if label.lower() in label_mapper:
return label_mapper[label]
label = label.replace("_", " ")
label = label[0].capitalize() + label[1:]
return label
def map_expt_name(expt_row):
# drop backbone and segmentation
if expt_row["pixel_confid"] == "None":
# should be only mahalanobis
pixel_confid = pixel_csf_mapper["baseline"]
else:
pixel_confid = pixel_csf_mapper[expt_row["pixel_confid"]]
image_confid = image_csf_mapper.get(expt_row["image_confid"])
if image_confid is None:
# aggregation case
if expt_row["image_confid"] in agg_mapper:
image_confid = agg_mapper[expt_row["image_confid"]]
else:
assert expt_row["image_confid"] == "all_simple"
image_confid = agg_mapper[expt_row["confid_name"]]
return f"{pixel_confid} + {image_confid}"
def get_unique_expt_name(expt_name: pd.Series, confid_name: pd.Series):
if isinstance(expt_name, str):
expt_name = pd.Series([expt_name])
if isinstance(confid_name, str):
confid_name = pd.Series([confid_name])
assert np.all(expt_name.index == confid_name.index)
df = expt_name.str.split("-", expand=True)
df.rename(
columns={0: "backbone", 1: "segmentation", 2: "pixel_confid", 3: "image_confid"},
inplace=True,
)
df["confid_name"] = confid_name
return df.apply(map_expt_name, axis=1)
def get_base_color(expt_name, return_idx=True) -> str:
pxl_csf, image_csf = expt_name.split(" + ")
img_methods = list(image_csf_mapper.values())
pxl_methods = list(pixel_csf_mapper.values())
color_idx = pxl_methods.index(pxl_csf)
if image_csf in img_methods:
color_idx = len(pxl_methods) + img_methods.index(image_csf)
if return_idx:
return color_idx
return color_palette[color_idx]
def get_marker(expt_name):
# depends only on aggregation
markers = ["o", "o", "o", "s", "p", "v", "D", "P", "X"]
for i, val in enumerate(agg_mapper.values()):
if val in expt_name:
return markers[i]
return "o"
def get_hue_colors_markers(expt_names, hue_incr=0.1) -> dict:
base_colors = [get_base_color(x) for x in expt_names]
# markers depend only on aggregation function
markers = {x: get_marker(x) for x in expt_names}
# count how often each color occurs
shades_counts = defaultdict(int)
for color_idx in base_colors:
shades_counts[color_idx] += 1
# for colors with more than one occurrence, use different shades
shades_idx = defaultdict(int)
hue_colors = {}
for color_idx, key in zip(base_colors, expt_names):
factor = max(0, 1 + hue_incr * shades_idx[color_idx])
hue_colors[key] = adjust_saturation(color_palette[color_idx], factor)
shades_idx[color_idx] += 1
return hue_colors, markers
def load_results(expt_group_dir, included_datasets=None):
all_fd_results = []
all_ood_results = []
all_configs = {}
for dataset_dir in expt_group_dir.iterdir():
if not dataset_dir.name.startswith("Dataset"):
continue
dataset_id = int(dataset_dir.name.removeprefix("Dataset"))
if included_datasets is not None and dataset_id not in included_datasets:
continue
fd_results, expt_configs = load_fd_results_hydra(
dataset_dir / "runs", csv_name="fd_metrics.csv"
)
ood_results = None
if dataset_id not in [503, 515]:
# no OOD for these datasets
ood_results, _ = load_fd_results_hydra(
dataset_dir / "runs", csv_name="ood_metrics.csv"
)
if len(expt_configs) == 0:
logger.warning(f"No experiment runs found for dataset {dataset_id}. Skipping...")
continue
# TODO check that expt IDs are consistent, ie the experiment dir (root_dir) in the dataframe is the same
# add dataset_id to expt_id to avoid ambiguity
fd_results["expt_id"] = str(dataset_id) + "_" + fd_results["expt_id"].astype(str)
expt_configs = {f"{dataset_id}_{i}": cfg for i, cfg in expt_configs.items()}
expt_id_to_name = {i: cfg.expt_name for i, cfg in expt_configs.items()}
expt_id_to_seed = {i: cfg.seed for i, cfg in expt_configs.items()}
try:
expt_id_to_fold = {i: cfg.datamodule.fold for i, cfg in expt_configs.items()}
except omegaconf.errors.ConfigKeyError:
# legacy configs
expt_id_to_fold = {i: cfg.datamodule.hparams.fold for i, cfg in expt_configs.items()}
fd_results["dataset"] = dataset_id
fd_results["expt_name"] = fd_results.expt_id.map(expt_id_to_name)
fd_results["expt_version"] = fd_results.root_dir.str.split("/").str[-1]
fd_results["seed"] = fd_results.expt_id.map(expt_id_to_seed)
fd_results["fold"] = fd_results.expt_id.map(expt_id_to_fold)
if "opt-aurc" in fd_results.columns and "aurc" in fd_results.columns:
fd_results["eaurc"] = fd_results["aurc"] - fd_results["opt-aurc"]
all_fd_results.append(fd_results)
if ood_results is not None and len(ood_results) > 0:
ood_results["expt_id"] = str(dataset_id) + "_" + ood_results["expt_id"].astype(str)
ood_results["expt_name"] = ood_results.expt_id.map(expt_id_to_name)
ood_results["expt_version"] = ood_results.root_dir.str.split("/").str[-1]
ood_results["dataset"] = dataset_id
ood_results["seed"] = ood_results.expt_id.map(expt_id_to_seed)
ood_results["fold"] = ood_results.expt_id.map(expt_id_to_fold)
all_ood_results.append(ood_results)
all_configs.update(expt_configs)
return (
pd.concat(all_fd_results, ignore_index=True),
pd.concat(all_ood_results, ignore_index=True) if len(all_ood_results) > 0 else None,
all_configs,
)
def filter_expts_for_comparison(fd_results, expt_name_confid_combinations=None):
# Include these experiments (multiple seeds):
if expt_name_confid_combinations is None:
# this is just the default overall comparison
expt_name_confid_combinations = [
("baseline-all_simple", "predictive_entropy_mean"),
("deep_ensemble-all_simple", "pairwise_dice"),
("mcdropout-all_simple", "pairwise_dice"),
("None-mahalanobis", "bottleneck.0.conv2"),
("None-mahalanobis", "bottleneck.0.blocks.0.conv2"), # updated state_dict naming
("None-mahalanobis", "model.1.submodule"),
("deep_ensemble-quality_regression", MAIN_SEG_METRIC),
("deep_ensemble-vae_mask_only", "elbo"),
# ("None-vae_image_and_mask", "elbo"),
]
if MAIN_SEG_METRIC == "generalized_dice":
expt_name_confid_combinations += [
("deep_ensemble-all_simple", "pairwise_gen_dice"),
("mcdropout-all_simple", "pairwise_gen_dice"),
]
elif MAIN_SEG_METRIC == "mean_dice":
expt_name_confid_combinations += [
("deep_ensemble-all_simple", "pairwise_mean_dice"),
("mcdropout-all_simple", "pairwise_mean_dice"),
]
filtered_df = []
for expt_name, confid_name in expt_name_confid_combinations:
if confid_name == "mean_dice":
# TODO this is a workaround because I changed some confidence names
# use the dice score for the only fg class for these datasets
filtered_df.append(
fd_results[
(fd_results.dataset.isin([500, 520, 521]))
& (fd_results.expt_name.str.contains(expt_name, regex=False))
& (fd_results.confid_name.str.contains("dice_0", regex=False))
]
)
filtered_df.append(
fd_results[
(fd_results.expt_name.str.contains(expt_name, regex=False))
& (fd_results.confid_name.str.contains(confid_name, regex=False))
]
)
return pd.concat(filtered_df)
def plot_confidence_vs_metric(
results_df: pd.DataFrame,
metric: str,
confid_name: str,
title=None,
plot_regression_line: bool = False,
normalize_confid=False,
show_diagonal_line=False,
**plot_kwargs,
):
fig, ax = plt.subplots()
# this is how the columns are named
metric_col = f"metric_{metric}"
confid_col = f"confid_{confid_name}"
# curr_ax.set_aspect("equal")
plot_data = results_df.copy()
# normalize confidence (min/max)
if normalize_confid:
normalized_confids = plot_data.groupby("expt_id", group_keys=False)[confid_col].apply(
lambda x: (x - x.min()) / (x.max() - x.min())
)
assert np.all(normalized_confids.index == plot_data.index)
plot_data[confid_col] = normalized_confids
sns.scatterplot(
x=confid_col,
y=metric_col,
hue="domain",
data=plot_data,
ax=ax,
alpha=0.8,
**plot_kwargs,
)
if show_diagonal_line:
ax.plot([0, 1], [0, 1], linestyle=":", color="black", alpha=0.3)
sns.move_legend(
ax,
loc="upper left",
bbox_to_anchor=(0, 1),
ncol=1,
title="Domain",
frameon=True,
)
if plot_regression_line:
# plot the regression line
sns.regplot(
x=confid_col,
y=metric_col,
data=plot_data,
ax=ax,
scatter=False,
color="black",
line_kws={"alpha": 0.7},
)
# curr_ax.set_ylabel(metric)
ax.set_ylabel(metric)
ax.set_xlabel("Confidence")
if title is not None:
ax.set_title(title)
return fig
# NOTE adapted from standard plots. lazy...
def plot_class_seg_metrics_across_domains(
df: pd.DataFrame, metric: str, included_domains: list = None, ax=None
):
plot_data = df.copy()
# match all columns that follow the pattern metric_classXX_metric, where XX are two digits
# class_metrics = [c for c in plot_data.columns if c.endswith(metric) and "metric_class" in c]
pattern = re.compile(r"metric_class\d\d_" + metric)
class_metrics = [c for c in plot_data.columns if pattern.match(c)]
if len(class_metrics) == 0:
plot_data.rename(columns={f"metric_{metric}": f"metric_class00_{metric}"}, inplace=True)
class_metrics = [
c for c in plot_data.columns if c.endswith(metric) and "metric_class" in c
]
plot_data = plot_data.melt(
id_vars=["domain", "case_id"],
value_vars=class_metrics,
var_name="class",
value_name=metric,
)
if included_domains is not None:
plot_data = plot_data[plot_data.domain.isin(included_domains)]
shift_order = (
plot_data.groupby("domain")[metric].median().sort_values(ascending=False).index.tolist()
)
if included_domains is not None:
shift_order = included_domains
if ax is None:
fig, ax = plt.subplots()
sns.boxplot(
data=plot_data,
x="domain",
y=metric,
hue="class",
order=shift_order,
fliersize=0,
ax=ax,
palette="gray",
fill=False,
)
sns.stripplot(
data=plot_data,
x="domain",
y=metric,
hue="class",
jitter=0.1,
dodge=True,
order=shift_order,
alpha=0.5,
ax=ax,
palette="rocket",
)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[len(handles) // 2 :], labels[len(labels) // 2 :])
if len(class_metrics) == 1:
# disable legend
ax.legend().set_visible(False)
return ax
# TODO maybe merge with the _with_ranking variant?
def plot_fd_comparison_across_datasets(
df, seg_metric, fd_metric, change_markers=False, show_rand_opt=False, **strip_kwargs
):
plot_data = df.copy()
plot_data = plot_data[plot_data.metric == seg_metric]
assert plot_data.domain.nunique() == 1
plot_data = plot_data.sort_values("expt_name")
# drop duplicates (I re-ran some experiments)
plot_data = plot_data.drop_duplicates(
subset=[x for x in plot_data.columns if x not in ["expt_version", "expt_id", "root_dir"]]
)
# make the expt_name and dataset description nicer
plot_data["legend_name"] = get_unique_expt_name(plot_data.expt_name, plot_data.confid_name)
plot_data["dataset"] = plot_data.dataset.map(dataset_mapper)
expt_order = order_expts(plot_data["legend_name"].unique().tolist())
ds_order = [x for x in dataset_mapper.values() if x in plot_data.dataset.unique()]
colors, markers = get_hue_colors_markers(expt_order, hue_incr=0.12 * (not change_markers))
# check for more subtle duplicates
for group, group_df in plot_data.groupby(["dataset", "legend_name"]):
num_seeds = group_df.seed.nunique()
num_folds = group_df.fold.nunique()
if len(group_df) != 5:
logger.warning(
f"Found {len(group_df)} results ({num_seeds} seeds and {num_folds} folds) for {group} but expected 5."
)
# either vary hue or markers...?
if not change_markers:
markers = {k: "o" for k in markers}
fig, ax = plt.subplots(figsize=get_figsize(), layout="constrained")
for expt_name, m in markers.items():
sns.stripplot(
data=plot_data[plot_data.legend_name == expt_name],
x="dataset",
y=fd_metric,
hue="legend_name",
ax=ax,
dodge=True,
order=ds_order,
palette=colors,
marker=m,
hue_order=expt_order,
**strip_kwargs,
)
# remove duplicates from legend and order by expt_order
handles, labels = ax.get_legend_handles_labels()
by_label = dict(zip(labels, handles))
# add vertical separators between datasets
for i in range(1, len(plot_data.dataset.unique())):
ax.axvline(i - 0.5, color="gray", linestyle=":", alpha=0.5)
if fd_metric == "norm-aurc":
ax.axhline(y=1, color="black", linestyle="--")
ax.set_ylim(bottom=-0.05)
if fd_metric.endswith("auc"):
ax.axhline(y=0.5, color="black", linestyle="--")
ax.set_ylim(top=1.05)
if (
fd_metric == "aurc"
and show_rand_opt
and {"rand-aurc", "opt-aurc"}.issubset(plot_data.columns)
):
sns.stripplot(
data=plot_data,
x="dataset",
y="rand-aurc",
hue="legend_name",
ax=ax,
dodge=True,
order=ds_order,
palette=["gray"] * len(expt_order),
hue_order=expt_order,
marker="$-$",
alpha=0.2,
jitter=0,
)
sns.stripplot(
data=plot_data,
x="dataset",
y="opt-aurc",
hue="legend_name",
ax=ax,
dodge=True,
order=ds_order,
palette=["gray"] * len(expt_order),
hue_order=expt_order,
marker="$-$",
alpha=0.2,
jitter=0,
)
# remove duplicates from legend and order by expt_order
ax.legend(
[
plt.Line2D([], [], marker=markers[x], color=by_label[x]._color, linestyle="")
for x in expt_order
],
expt_order,
loc="lower center",
ncols=2,
bbox_to_anchor=(0.5, 1),
ncol=1,
title=None,
frameon=False,
)
return fig
def plot_fd_comparison_across_datasets_multi(
df, seg_metric, fd_metric, change_markers=False, show_rand_opt=False, **strip_kwargs
):
# fd_metric can be a list
if isinstance(fd_metric, str):
return plot_fd_comparison_across_datasets(
df, seg_metric, fd_metric, change_markers, show_rand_opt, **strip_kwargs
)
plot_data = df.copy()
plot_data = plot_data[plot_data.metric == seg_metric]
assert plot_data.domain.nunique() == 1
plot_data = plot_data.sort_values("expt_name")
# drop duplicates (I re-ran some experiments)
plot_data = plot_data.drop_duplicates(
subset=[x for x in plot_data.columns if x not in ["expt_version", "expt_id", "root_dir"]]
)
# make the expt_name and dataset description nicer
plot_data["legend_name"] = get_unique_expt_name(plot_data.expt_name, plot_data.confid_name)
plot_data["dataset"] = plot_data.dataset.map(dataset_mapper)
expt_order = order_expts(plot_data["legend_name"].unique().tolist())
ds_order = [x for x in dataset_mapper.values() if x in plot_data.dataset.unique()]
colors, markers = get_hue_colors_markers(expt_order, hue_incr=0.12 * (not change_markers))
# check for more subtle duplicates
for group, group_df in plot_data.groupby(["dataset", "legend_name"]):
num_seeds = group_df.seed.nunique()
num_folds = group_df.fold.nunique()
if len(group_df) != 5:
logger.warning(
f"Found {len(group_df)} results ({num_seeds} seeds and {num_folds} folds) for {group} but expected 5."
)
# either vary hue or markers...?
if not change_markers:
markers = {k: "o" for k in markers}
fig, axes = plt.subplots(
len(fd_metric), 1, figsize=(PAPER_TEXTWIDTH, PAPER_TEXTHEIGHT * 0.95), layout="constrained"
)
for idx, fdm in enumerate(fd_metric):
ax = axes[idx]
for expt_name, m in markers.items():
sns.stripplot(
data=plot_data[plot_data.legend_name == expt_name],
x="dataset",
y=fdm,
hue="legend_name",
ax=ax,
dodge=True,
order=ds_order,
palette=colors,
marker=m,
hue_order=expt_order,
**strip_kwargs,
)
# remove duplicates from legend and order by expt_order
handles, labels = ax.get_legend_handles_labels()
by_label = dict(zip(labels, handles))
# add vertical separators between datasets
for i in range(1, len(plot_data.dataset.unique())):
ax.axvline(i - 0.5, color="gray", linestyle=":", alpha=0.5)
if fdm == "norm-aurc":
ax.axhline(y=1, color="black", linestyle="--")
ax.set_ylim(bottom=-0.05)
if fdm.endswith("auc"):
ax.axhline(y=0.5, color="black", linestyle="--")
ax.set_ylim(top=1.05)
if (
fdm == "aurc"
and show_rand_opt
and {"rand-aurc", "opt-aurc"}.issubset(plot_data.columns)
):
sns.stripplot(
data=plot_data,
x="dataset",
y="rand-aurc",
hue="legend_name",
ax=ax,
dodge=True,
order=ds_order,
palette=["gray"] * len(expt_order),
hue_order=expt_order,
marker="$-$",
alpha=0.2,
jitter=0,
)
sns.stripplot(
data=plot_data,
x="dataset",
y="opt-aurc",
hue="legend_name",
ax=ax,
dodge=True,
order=ds_order,
palette=["gray"] * len(expt_order),
hue_order=expt_order,
marker="$-$",
alpha=0.2,
jitter=0,
)
# remove duplicates from legend and order by expt_order
if idx == 0:
ax.legend(
[
plt.Line2D([], [], marker=markers[x], color=by_label[x]._color, linestyle="")
for x in expt_order
],
expt_order,
# loc="lower center",
# bbox_to_anchor=(0.5, 1),
loc="upper right",
bbox_to_anchor=(1, 1),
ncols=2,
title=None,
# frameon=False,
)
else:
ax.legend().set_visible(False)
if idx != len(fd_metric) - 1:
ax.set_xlabel("")
return fig
def plot_fd_comparison_across_datasets_with_ranking(
df, seg_metric, fd_metric, show_rand_opt=False, **strip_kwargs
):
plot_data = df.copy()
plot_data = plot_data[plot_data.metric == seg_metric]
assert plot_data.domain.nunique() == 1
plot_data = plot_data.sort_values("expt_name")
# drop duplicates (I re-ran some experiments)
plot_data = plot_data.drop_duplicates(
subset=[x for x in plot_data.columns if x not in ["expt_version", "expt_id", "root_dir"]]
)
# make the expt_name and dataset description nicer
plot_data["legend_name"] = get_unique_expt_name(plot_data.expt_name, plot_data.confid_name)
plot_data["dataset"] = plot_data.dataset.map(dataset_mapper)
expt_order = order_expts(plot_data["legend_name"].unique().tolist())
ds_order = [x for x in dataset_mapper.values() if x in plot_data.dataset.unique()]
colors, markers = get_hue_colors_markers(expt_order, hue_incr=0.12)
# check for more subtle duplicates
for group, group_df in plot_data.groupby(["dataset", "legend_name"]):
num_seeds = group_df.seed.nunique()
num_folds = group_df.fold.nunique()
if len(group_df) != 5:
logger.warning(
f"Found {len(group_df)} results ({num_seeds} seeds and {num_folds} folds) for {group} but expected 5."
)
fig, axes = plt.subplots(
2,
1,
figsize=get_figsize(),
layout="constrained",
gridspec_kw={"height_ratios": [1, 3.5]},
sharex=True,
)
# upper plot:
ax = axes[0]
# compute ranking based on mean fd_metric
# adapted from ranking plot
group_df = plot_data.groupby(["dataset", "legend_name"])
for _, df in group_df:
if "deep_ensemble" in df.expt_name.unique()[0]:
assert (
df.seed.nunique() <= 3
), f"Found {df.seed.nunique()} seeds for {df.expt_name.unique()[0]}"
else:
assert (
df.seed.nunique() <= 5
), f"Found {df.seed.nunique()} seeds for {df.expt_name.unique()[0]}"
avg_metric = group_df[fd_metric].agg("mean")
higher_better = True if fd_metric == "norm-aurc" else False
# for correlation metrics, negative values are better (risk vs confidence)
if fd_metric not in ["aurc", "eaurc", "norm-aurc", "spearman", "pearson"]:
raise ValueError(f"Unknown metric {fd_metric}")
avg_metric_rank = avg_metric.groupby("dataset").rank(ascending=not higher_better).reset_index()
sns.pointplot(
data=avg_metric_rank,
x="dataset",
y=fd_metric,
hue="legend_name",
dodge=False,
linestyles="None",
markers=MarkerStyle("s").scaled(10, 1),
ax=ax,
palette=colors,
order=ds_order,
hue_order=expt_order,
)
ax.set_ylabel("Ranking")
ax.set_yticks(range(1, len(expt_order) + 1))
ax.set_ylim(1 - 0.4, len(expt_order) + 0.4)
# Get the handles and labels from the plot
handles, labels = ax.get_legend_handles_labels()
# # Create custom handles
# custom_handles = [
# plt.Line2D([], [], marker="o", color=h._color, linestyle="") for h in handles
# ]
# Create the legend with the custom handles
# ax.legend(
# custom_handles,
# labels,
# loc="lower center",
# ncol=2,
# bbox_to_anchor=(0.5, 1),
# title=None,
# frameon=False,
# )
ax.legend().set_visible(False)
# lower plot:
ax = axes[1]
sns.stripplot(
data=plot_data,
x="dataset",
y=fd_metric,
hue="legend_name",
ax=ax,
dodge=True,
order=ds_order,
palette=colors,
hue_order=expt_order,
**strip_kwargs,
)
# ax.legend().set_visible(False)
# Get the handles and labels from the plot
handles, labels = ax.get_legend_handles_labels()
# add vertical separators between datasets
for i in range(1, len(plot_data.dataset.unique())):
ax.axvline(i - 0.5, color="gray", linestyle=":", alpha=0.5)
if fd_metric == "norm-aurc":
ax.axhline(y=1, color="black", linestyle="--")
ax.set_ylim(bottom=-0.05)
if fd_metric.endswith("auc"):
ax.axhline(y=0.5, color="black", linestyle="--")
ax.set_ylim(top=1.05)
if (
fd_metric == "aurc"
and show_rand_opt
and {"rand-aurc", "opt-aurc"}.issubset(plot_data.columns)
):
sns.stripplot(
data=plot_data,
x="dataset",
y="rand-aurc",
hue="legend_name",
ax=ax,
dodge=True,
order=ds_order,
palette=["gray"] * len(expt_order),
hue_order=expt_order,
marker="$-$",
alpha=0.2,
jitter=0,
)
sns.stripplot(
data=plot_data,
x="dataset",
y="opt-aurc",
hue="legend_name",
ax=ax,
dodge=True,
order=ds_order,
palette=["gray"] * len(expt_order),
hue_order=expt_order,
marker="$-$",
alpha=0.2,
jitter=0,
)
handles, labels = ax.get_legend_handles_labels()
handles = handles[: len(expt_order)]
labels = labels[: len(expt_order)]
# ax.legend().set_visible(False)
ax.legend(
handles,
labels,
loc="upper left",
ncol=2,
bbox_to_anchor=(0, 1),
title=None,
frameon=True,
)
return fig
def plot_ood_comparison_across_datasets(df, ood_metric, domain="all_ood_"):
plot_data = df.copy()
plot_data = plot_data[plot_data.domain == domain]
# drop duplicates (I re-ran some experiments)
plot_data = plot_data.drop_duplicates(
subset=[x for x in plot_data.columns if x not in ["expt_version", "expt_id", "root_dir"]]
)
# make the expt_name and dataset description nicer
plot_data["legend_name"] = get_unique_expt_name(plot_data.expt_name, plot_data.confid_name)
plot_data["dataset"] = plot_data.dataset.map(dataset_mapper)
expt_order = order_expts(plot_data["legend_name"].unique().tolist())
colors, markers = get_hue_colors_markers(expt_order)
# check for more subtle duplicates
for group, group_df in plot_data.groupby(["dataset", "legend_name"]):
num_seeds = group_df.seed.nunique()
num_folds = group_df.fold.nunique()
if len(group_df) != 5:
logger.warning(
f"Found {len(group_df)} results ({num_seeds} seeds and {num_folds} folds) for {group} but expected 5."
)
fig, ax = plt.subplots(figsize=get_figsize(textwidth_factor=0.8))
sns.stripplot(
data=plot_data,
x="dataset",
y=ood_metric,
hue="legend_name",
ax=ax,
dodge=True,
order=[x for x in dataset_mapper.values() if x in plot_data.dataset.unique()],
palette=colors,
hue_order=expt_order,
)
sns.move_legend(
ax,
"upper left",
ncols=2,
bbox_to_anchor=(0, 1),
title=None,
)
# add vertical separators between datasets
for i in range(1, len(plot_data.dataset.unique())):
ax.axvline(i - 0.5, color="gray", linestyle=":", alpha=0.5)
if ood_metric.endswith("auc"):
ax.axhline(y=0.5, color="black", linestyle="--")
ax.set_ylim(top=1.05)
fig.tight_layout()
return fig
def plot_risk_coverage_curves(fd_results, risk_metric):
# Each row in fd_results is a single experiment and we plot the risk-coverage curve for each of them
# We need to load the curve npz files and then plot them
assert fd_results.dataset.nunique() == 1
plot_data = filter_expts_for_comparison(fd_results)
assert plot_data.domain.nunique() == 1
plot_data = plot_data[plot_data.metric == risk_metric]
fig, ax = plt.subplots()
# make the expt_name and dataset description nicer
plot_data["legend_name"] = get_unique_expt_name(plot_data.expt_name, plot_data.confid_name)
expt_order = order_expts(plot_data.legend_name.unique().tolist())
colors, markers = get_hue_colors_markers(expt_order)
num_runs_per_expt = plot_data.groupby("legend_name").size()
num_seeds_per_expt = plot_data.groupby("legend_name").seed.nunique()
num_folds_per_expt = plot_data.groupby("legend_name").fold.nunique()
if not np.all(num_runs_per_expt == num_seeds_per_expt):
logger.warning(
"Found different number of runs per experiment. "
"Maybe some seeds were re-run? Consider dropping them manually."
)
for _, row in plot_data.iterrows():
curve_file = row.file_risk_coverage_curve
if not Path(curve_file).is_absolute():
curve_file = f"{row.root_dir}/analysis/{curve_file}"
curr_curve = np.load(curve_file)
num_seeds = num_seeds_per_expt.loc[row.legend_name]
num_folds = num_folds_per_expt.loc[row.legend_name]
plt.plot(
curr_curve["coverage"],
curr_curve["risk"],
"-",
label=row.legend_name,
color=colors[row.legend_name],
alpha=0.5 if max(num_seeds, num_folds) > 1 else 1,
)
ax.set_xlabel("Coverage")
ax.set_ylabel("Risk")
ax.legend()
# remove duplicates from legend and order by expt_order
handles, labels = ax.get_legend_handles_labels()
by_label = dict(zip(labels, handles))
ax.legend([by_label[x] for x in expt_order], expt_order)
sns.move_legend(
ax,
"lower center",
ncols=2,
bbox_to_anchor=(0.5, 1),
ncol=1,
title=None,
frameon=False,
)
return fig
def make_table_dice_vs_surf_dist(
fd_results, fd_metric, output_file, surface_distance_metric="mean_surface_dice"
):
plot_data = filter_expts_for_comparison(fd_results)
plot_data = plot_data[plot_data.metric.isin([MAIN_SEG_METRIC, surface_distance_metric])]
assert plot_data.domain.nunique() == 1
plot_data = plot_data.drop_duplicates(
subset=[x for x in plot_data.columns if x not in ["expt_version", "expt_id", "root_dir"]]
)
# check for more subtle duplicates
for group, group_df in plot_data.groupby(["expt_name", "dataset", "confid_name", "metric"]):
num_seeds = group_df.seed.nunique()
num_folds = group_df.fold.nunique()
if len(group_df) > max(num_folds, num_seeds):
logger.warning(
f"Found {len(group_df)} results for {group}."
"Maybe some seeds were re-run? Consider dropping them manually."
)