-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualization_utils.py
More file actions
2745 lines (2196 loc) · 115 KB
/
Copy pathvisualization_utils.py
File metadata and controls
2745 lines (2196 loc) · 115 KB
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
"""
H. Pylori Contamination Detection - Visualization Utilities Module
==================================================================
OVERVIEW
--------
This module consolidates all visualization and interpretability functions for the
H. Pylori contamination detection system. It provides a unified API for:
- Gradient-based attribution (Grad-CAM) for model interpretability
- Training metrics visualization (learning curves, confusion matrices)
- Diagnostic metrics (ROC curves, Precision-Recall curves, probability distributions)
- Interpretable patch-level heatmap generation with attention visualization
PURPOSE
-------
Eliminates code duplication between train.py and generate_visuals.py by providing
a single source of truth for all PNG image generation. Can be used:
- During training to track convergence and model behavior
- Post-training for comprehensive evaluation reporting
- For clinical interpretation and model debugging
- In custom analysis pipelines requiring specific visualizations
ARCHITECTURE
------------
This is a STATELESS UTILITY MODULE: All functions are independent, take explicit
inputs, and produce explicit outputs. No class instantiation or module state required.
Functions are organized into three categories:
1. CORE GRADIENT ATTRIBUTION
- generate_gradcam(): Input-level gradient saliency (model-agnostic)
- Works with any PyTorch backbone architecture
2. METRIC VISUALIZATIONS (Training pipeline metrics)
- plot_learning_curves(): Training/validation loss and accuracy over epochs
- plot_confusion_matrix(): Patient-level 2x2 confusion matrix
- plot_probability_histogram(): Distribution of predicted probabilities
- plot_roc_curve(): Receiver Operating Characteristic with AUC
- plot_pr_curve(): Precision-Recall curve with Average Precision
3. INTERPRETABILITY VISUALIZATION
- plot_gradcam_pair(): Side-by-side original patch + heatmap overlay for
top-ranked predictions and false negatives
HOW IT WORKS
------------
GRADIENT-BASED ATTRIBUTION (generate_gradcam):
1. Forward pass: Input batch → backbone → logits
2. Loss computation: Sum logits (proxy for feature signal magnitude)
3. Backward pass: Compute ∇(loss)/∇(input)
4. Attribution: Absolute gradients summed across channels
5. Smoothing: Apply Gaussian blur (σ=1.5) to reduce noise
6. Normalization: Scale to [0, 1] per-sample range
METRIC VISUALIZATIONS:
- All functions use matplotlib for consistent styling
- Patient-level aggregation (not patch-level)
- Auto-creates output directory if needed
- Closes figures after saving (prevents memory accumulation)
INTERPRETABILITY:
- Combines original patch image with jet-colormap heatmap overlay
- Includes attention score and predicted probability in titles
- Different naming convention for false negatives (FN_ prefix)
- Denormalizes to ImageNet statistics for visual inspection
USAGE
-----
IMPORT STATEMENT:
from visualization_utils import (
generate_gradcam, plot_learning_curves, plot_confusion_matrix,
plot_probability_histogram, plot_roc_curve, plot_pr_curve, plot_gradcam_pair
)
BASIC USAGE EXAMPLES:
# Compute Grad-CAM for a batch of images
heatmaps, probs = generate_gradcam(model.backbone, img_batch)
# Plot training curves
history = {'train_loss': [...], 'val_loss': [...],
'train_acc': [...], 'val_acc': [...]}
plot_learning_curves(history, 'results/learning_curves.png')
# Plot confusion matrix
plot_confusion_matrix(all_labels, all_preds, 'results/confusion_matrix.png')
# Plot probability distribution
plot_probability_histogram(all_probs, all_labels, 'results/histogram.png')
# Plot ROC and PR curves
plot_roc_curve(all_labels, all_probs, 'results/roc.png')
plot_pr_curve(all_labels, all_probs, 'results/pr.png')
# Visualize top prediction with Grad-CAM
plot_gradcam_pair(
patch_img=patch_tensor, # (1, C, H, W) or (C, H, W)
heatmap=heatmap_array, # (H, W) normalized to [0,1]
patient_id='patient_123',
rank=0, # Rank among top patches
patch_idx=42,
attention_score=0.8234,
prob=0.95,
is_false_negative=False,
output_dir='results/gradcam_samples'
)
FUNCTION REFERENCE
------------------
generate_gradcam(backbone, input_batch, target_layer=None)
Generates interpretable saliency heatmap using input-level gradients.
Args:
backbone: Neural network (ConvNeXt-Tiny or ResNet50)
input_batch: (B, C, H, W) tensor on GPU/CPU
target_layer: Deprecated (kept for backwards compatibility)
Returns:
heatmap_np: (B, 1, H, W) normalized to [0, 1]
probs: (B, 2) softmax probabilities for [negative, positive]
plot_learning_curves(history, output_path, figsize=(12, 5))
Args:
history: Dict with keys ['train_loss', 'val_loss', 'train_acc', 'val_acc']
output_path: PNG save location
figsize: Matplotlib figure size
Output: 2-panel plot (loss on left, accuracy on right)
plot_confusion_matrix(all_labels, all_preds, output_path, figsize=(8, 6))
Args:
all_labels: (N,) binary true labels
all_preds: (N,) binary predicted labels
output_path: PNG save location
figsize: Matplotlib figure size
Output: 2x2 confusion matrix heatmap
plot_probability_histogram(all_probs, all_labels, output_path, figsize=(8, 6))
Args:
all_probs: (N,) predicted probabilities [0, 1]
all_labels: (N,) binary true labels
output_path: PNG save location
figsize: Matplotlib figure size
Output: Histogram with negative/positive overlay + 0.5 threshold line
plot_roc_curve(all_labels, all_probs, output_path)
Args:
all_labels: (N,) binary true labels
all_probs: (N,) predicted probabilities [0, 1]
output_path: PNG save location
Output: ROC curve with AUC score in legend
plot_pr_curve(all_labels, all_probs, output_path)
Args:
all_labels: (N,) binary true labels
all_probs: (N,) predicted probabilities [0, 1]
output_path: PNG save location
Output: Precision-Recall curve with Average Precision in legend
plot_gradcam_pair(patch_img, heatmap, patient_id, rank, patch_idx,
attention_score, prob, is_false_negative, output_dir)
Args:
patch_img: (1, C, H, W) or (C, H, W) tensor
heatmap: (H, W) saliency array in [0, 1]
patient_id: String identifier
rank: Integer rank (0 for top positive)
patch_idx: Patch index within patient
attention_score: MIL attention weight [0, 1]
prob: Positive class probability [0, 1]
is_false_negative: Boolean (affects filename/title)
output_dir: Directory to save PNG
Returns: Path to saved PNG file
Output: Side-by-side (original | heatmap overlay)
INTEGRATION POINTS
------------------
Called from:
- train.py: During model evaluation after each epoch
- generate_visuals.py: After loading trained checkpoint for reporting
- Custom analysis scripts: For post-hoc model interpretation
DEPENDENCIES
------------
- PyTorch: tensor operations, gradient computation
- NumPy: array manipulation, statistics
- Matplotlib: figure generation and styling
- Scipy: gaussian_filter for smoothing
- Scikit-learn: metrics (confusion matrix, ROC/PR curves)
NOTES
-----
- All functions assume inputs are properly preprocessed (tensors on correct device)
- Grad-CAM uses model.eval() internally to disable stochastic components
- Probability histograms use patient-level aggregations (not per-patch)
- Heatmap normalization uses per-sample min-max (not global statistics)
- Gaussian smoothing (σ=1.5) removes interpolation artifacts while preserving edges
- Output figures automatically close after saving (prevents matplotlib state accumulation)
- All visualizations use patient-level metrics, not patch-level aggregations
"""
import torch
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
import os
from scipy.ndimage import gaussian_filter
from sklearn.metrics import (
confusion_matrix, ConfusionMatrixDisplay,
roc_curve, auc, precision_recall_curve, average_precision_score
)
# ============================================================================
# CORE GRADIENT ATTRIBUTION (used by both train.py and generate_visuals.py)
# ============================================================================
def generate_gradcam(backbone, input_batch, target_layer=None):
"""
Generates interpretable heatmap using input-level gradient saliency.
This is more robust than layer-specific Grad-CAM and works for any architecture.
Approach: Compute gradient of output with respect to input.
Shows which pixels matter most for the backbone's feature extraction.
Args:
backbone: Neural network backbone (ConvNeXt or ResNet)
input_batch: Image tensor (B, C, H, W) on DEVICE
target_layer: Deprecated parameter (kept for backwards compatibility)
Returns:
heatmap_np: Normalized saliency heatmap (B, 1, H, W) in [0, 1]
probs: Softmax probabilities (B, num_classes)
"""
backbone.eval()
# Create input with requires_grad to compute gradients
input_batch.requires_grad_(True)
# Forward pass
with torch.enable_grad():
logits = backbone(input_batch)
# Flatten if needed
if len(logits.shape) > 2:
logits = torch.flatten(logits, 1)
# Create a scalar loss: sum of features (positive class signal)
# For clinical safety: higher feature magnitude = more signal
loss = logits.sum()
# Backward to compute gradients at input
backbone.zero_grad()
loss.backward()
# Get gradients
gradients = input_batch.grad
if gradients is None:
batch_size = input_batch.shape[0]
return np.zeros((batch_size, 1, input_batch.shape[2], input_batch.shape[3])), np.zeros((batch_size, 2))
# Compute absolute gradients, average across channels
abs_grads = torch.abs(gradients) # (B, C, H, W)
saliency = torch.sum(abs_grads, dim=1, keepdim=True) # (B, 1, H, W)
# Convert to numpy
heatmap_np = saliency.detach().cpu().numpy()
# Process each sample in batch
for b in range(heatmap_np.shape[0]):
hmap = heatmap_np[b, 0] # (H, W)
# Normalize [0, 1]
hmap_min = hmap.min()
hmap = hmap - hmap_min
hmap_max = hmap.max()
if hmap_max > 0:
hmap = hmap / hmap_max
# Apply Gaussian smoothing to reduce noise while preserving structure
hmap = gaussian_filter(hmap, sigma=1.5)
# Final normalization after smoothing
hmap = np.clip(hmap, 0, 1)
hmap_min = hmap.min()
hmap = hmap - hmap_min
hmap_max = hmap.max()
if hmap_max > 0:
hmap = hmap / hmap_max
heatmap_np[b, 0] = hmap
# Get probabilities
with torch.no_grad():
probs = F.softmax(logits, dim=1).detach().cpu().numpy()
# Detach input
input_batch.requires_grad_(False)
return heatmap_np, probs
# ============================================================================
# METRIC VISUALIZATIONS
# ============================================================================
def plot_learning_curves(history, output_path, figsize=(12, 5)):
"""
Plot training and validation loss/accuracy curves.
Args:
history: Dict with keys ['train_loss', 'val_loss', 'train_acc', 'val_acc']
output_path: Path to save PNG file
figsize: Figure size tuple
"""
plt.figure(figsize=figsize)
# Loss Plot
plt.subplot(1, 2, 1)
plt.plot(history['train_loss'], label='Train Loss', color='tab:blue', linestyle='--')
plt.plot(history['val_loss'], label='Val Loss', color='tab:blue')
plt.title('Patient-Level Loss Convergence')
plt.xlabel('Epochs')
plt.ylabel('Focal Loss')
plt.legend()
# Accuracy Plot
plt.subplot(1, 2, 2)
plt.plot(history['train_acc'], label='Train Acc', color='tab:orange', linestyle='--')
plt.plot(history['val_acc'], label='Val Acc', color='tab:orange')
plt.title('Patient-Level Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.tight_layout()
plt.savefig(output_path)
plt.close()
def plot_confusion_matrix(all_labels, all_preds, output_path, figsize=(8, 6)):
"""
Plot patient-level confusion matrix.
Args:
all_labels: True labels (binary)
all_preds: Predicted labels (binary)
output_path: Path to save PNG file
figsize: Figure size tuple
"""
cm = confusion_matrix(all_labels, all_preds)
plt.figure(figsize=figsize)
disp = ConfusionMatrixDisplay(cm, display_labels=['Negative', 'Positive'])
disp.plot(cmap='Blues')
plt.title('Patient-Level Confusion Matrix')
plt.tight_layout()
plt.savefig(output_path)
plt.close()
def plot_combined_confusion_matrices(fold_cms, output_path, figsize=(16, 12)):
"""
Plot a dashboard of all fold confusion matrices plus overall combined matrix.
Args:
fold_cms (list): List of 5 confusion matrices (2x2 numpy arrays), one per fold
output_path (str): Path to save PNG file
figsize (tuple): Figure size (width, height)
Creates a 2x3 grid showing:
- Fold 0, 1, 2, 3, 4 (top 2 rows)
- Overall combined matrix (bottom right)
"""
fig, axes = plt.subplots(2, 3, figsize=figsize)
axes = axes.flatten() # Flatten for easier indexing
# Plot individual fold matrices
for fold_idx, cm in enumerate(fold_cms):
ax = axes[fold_idx]
disp = ConfusionMatrixDisplay(cm, display_labels=['Negative', 'Positive'])
disp.plot(ax=ax, cmap='Blues', values_format='d')
ax.set_title(f'Fold {fold_idx} Confusion Matrix', fontsize=12, fontweight='bold')
# Compute and plot overall combined matrix
overall_cm = sum(fold_cms)
ax = axes[5]
disp = ConfusionMatrixDisplay(overall_cm, display_labels=['Negative', 'Positive'])
disp.plot(ax=ax, cmap='Greens', values_format='d')
ax.set_title('Overall Combined (All Folds)', fontsize=12, fontweight='bold')
fig.suptitle('DeepHP Pre-training: Confusion Matrices Across All Folds',
fontsize=14, fontweight='bold', y=0.995)
plt.tight_layout()
plt.savefig(output_path, dpi=150, bbox_inches='tight')
plt.close()
def plot_probability_histogram(all_probs, all_labels, output_path, figsize=(8, 6)):
"""
Plot predicted probability distribution.
Args:
all_probs: Predicted probabilities (patient-level)
all_labels: True labels (binary)
output_path: Path to save PNG file
figsize: Figure size tuple
"""
plt.figure(figsize=figsize)
plt.hist(all_probs[all_labels == 0], bins=20, alpha=0.5, label='Actual Negative', color='blue')
plt.hist(all_probs[all_labels == 1], bins=20, alpha=0.5, label='Actual Positive', color='red')
plt.axvline(x=0.5, color='black', linestyle='--', label='Threshold (0.5)')
plt.xlabel('Predicted Probability (Positive Class)')
plt.ylabel('Patient Count')
plt.title('Patient-Level Probability Distribution')
plt.legend()
plt.tight_layout()
plt.savefig(output_path)
plt.close()
def plot_roc_curve(all_labels, all_probs, output_path):
"""
Plot ROC curve with AUC score.
Args:
all_labels: True labels (binary)
all_probs: Predicted probabilities
output_path: Path to save PNG file
"""
fpr, tpr, _ = roc_curve(all_labels, all_probs)
roc_auc = auc(fpr, tpr)
plt.figure()
plt.plot(fpr, tpr, color='blue', lw=2, label=f'ROC (AUC = {roc_auc:.4f})')
plt.plot([0, 1], [0, 1], color='red', lw=2, linestyle='--', label='Random Classifier')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Patient-Level ROC Curve')
plt.legend(loc='lower right')
plt.tight_layout()
plt.savefig(output_path)
plt.close()
def plot_pr_curve(all_labels, all_probs, output_path):
"""
Plot Precision-Recall curve with Average Precision.
Args:
all_labels: True labels (binary)
all_probs: Predicted probabilities
output_path: Path to save PNG file
"""
precision, recall, _ = precision_recall_curve(all_labels, all_probs)
avg_prec = average_precision_score(all_labels, all_probs)
plt.figure()
plt.plot(recall, precision, color='green', lw=2, label=f'PR (AP = {avg_prec:.4f})')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.ylim([0.0, 1.05])
plt.xlim([0.0, 1.0])
plt.title('Patient-Level Precision-Recall Curve')
plt.legend(loc='lower left')
plt.tight_layout()
plt.savefig(output_path)
plt.close()
def plot_combined_pr_roc_curves(fold_data_list, output_path, figsize=(16, 12)):
"""
Plot a dashboard of PR and ROC curves for all folds.
Args:
fold_data_list (list): List of 5 dicts, each with 'labels' and 'probs' keys
output_path (str): Path to save PNG file
figsize (tuple): Figure size (width, height)
Creates a 5x2 grid showing:
- Column 1: ROC curves for folds 0-4
- Column 2: PR curves for folds 0-4
"""
fig, axes = plt.subplots(5, 2, figsize=figsize)
colors_roc = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd'] # 5 distinct colors
colors_pr = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']
for fold_idx, fold_data in enumerate(fold_data_list):
labels = fold_data['labels']
probs = fold_data['probs']
# ROC curve (left column)
ax_roc = axes[fold_idx, 0]
fpr, tpr, _ = roc_curve(labels, probs)
roc_auc = auc(fpr, tpr)
ax_roc.plot(fpr, tpr, color=colors_roc[fold_idx], lw=2.5,
label=f'ROC (AUC = {roc_auc:.4f})')
ax_roc.plot([0, 1], [0, 1], color='gray', lw=1.5, linestyle='--', alpha=0.7)
ax_roc.set_xlim([0.0, 1.0])
ax_roc.set_ylim([0.0, 1.05])
ax_roc.set_xlabel('False Positive Rate', fontsize=10)
ax_roc.set_ylabel('True Positive Rate', fontsize=10)
ax_roc.set_title(f'Fold {fold_idx} - ROC Curve', fontsize=11, fontweight='bold')
ax_roc.legend(loc='lower right', fontsize=9)
ax_roc.grid(True, alpha=0.3)
# PR curve (right column)
ax_pr = axes[fold_idx, 1]
precision, recall, _ = precision_recall_curve(labels, probs)
avg_prec = average_precision_score(labels, probs)
ax_pr.plot(recall, precision, color=colors_pr[fold_idx], lw=2.5,
label=f'PR (AP = {avg_prec:.4f})')
ax_pr.set_xlim([0.0, 1.0])
ax_pr.set_ylim([0.0, 1.05])
ax_pr.set_xlabel('Recall', fontsize=10)
ax_pr.set_ylabel('Precision', fontsize=10)
ax_pr.set_title(f'Fold {fold_idx} - Precision-Recall Curve', fontsize=11, fontweight='bold')
ax_pr.legend(loc='lower left', fontsize=9)
ax_pr.grid(True, alpha=0.3)
fig.suptitle('DeepHP Pre-training: ROC & PR Curves Across All Folds',
fontsize=14, fontweight='bold', y=0.995)
plt.tight_layout()
plt.savefig(output_path, dpi=150, bbox_inches='tight')
plt.close()
def plot_threshold_analysis(all_labels, all_probs, output_path, figsize=(14, 8)):
"""
Plot performance metrics across different decision thresholds.
Shows how Sensitivity, Specificity, Precision, Recall, Accuracy, and F1
vary as the decision threshold changes from 0 to 1. Helps identify optimal
thresholds for different clinical criteria (high sensitivity vs specificity).
Args:
all_labels: True labels (binary)
all_probs: Predicted probabilities
output_path: Path to save PNG file
figsize: Figure size tuple
"""
from sklearn.metrics import (
precision_score, recall_score, f1_score, accuracy_score,
confusion_matrix
)
# Generate thresholds from 0 to 1
thresholds = np.linspace(0, 1, 101)
metrics_by_threshold = {
'Sensitivity': [],
'Specificity': [],
'Precision': [],
'Recall': [],
'Accuracy': [],
'F1_Score': []
}
for threshold in thresholds:
# Convert probabilities to binary predictions using this threshold
preds = (np.array(all_probs) >= threshold).astype(int)
# Handle edge cases (all predictions same class)
if len(np.unique(preds)) == 1:
# If all predictions are same, metrics become undefined
tn, fp, fn, tp = confusion_matrix(all_labels, preds).ravel() if len(np.unique(all_labels)) > 1 else (0, 0, 0, 0)
else:
tn, fp, fn, tp = confusion_matrix(all_labels, preds).ravel()
# Calculate metrics
sensitivity = tp / (tp + fn) if (tp + fn) > 0 else 0
specificity = tn / (tn + fp) if (tn + fp) > 0 else 0
precision = precision_score(all_labels, preds, zero_division=0)
recall = recall_score(all_labels, preds, zero_division=0)
accuracy = accuracy_score(all_labels, preds)
f1 = f1_score(all_labels, preds, zero_division=0)
metrics_by_threshold['Sensitivity'].append(sensitivity)
metrics_by_threshold['Specificity'].append(specificity)
metrics_by_threshold['Precision'].append(precision)
metrics_by_threshold['Recall'].append(recall)
metrics_by_threshold['Accuracy'].append(accuracy)
metrics_by_threshold['F1_Score'].append(f1)
# Find optimal thresholds for different objectives
optimal_f1_idx = np.argmax(metrics_by_threshold['F1_Score'])
optimal_f1_threshold = thresholds[optimal_f1_idx]
optimal_f1_value = metrics_by_threshold['F1_Score'][optimal_f1_idx]
# Youden's J statistic (maximizes Sensitivity + Specificity - 1)
youden_j = [s + sp - 1 for s, sp in zip(metrics_by_threshold['Sensitivity'], metrics_by_threshold['Specificity'])]
optimal_j_idx = np.argmax(youden_j)
optimal_j_threshold = thresholds[optimal_j_idx]
optimal_j_value = youden_j[optimal_j_idx]
# Create visualization
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=figsize)
# Panel 1: Core metrics
ax1.plot(thresholds, metrics_by_threshold['Sensitivity'], label='Sensitivity (Recall)', linewidth=2.5, color='#2E86AB')
ax1.plot(thresholds, metrics_by_threshold['Specificity'], label='Specificity', linewidth=2.5, color='#A23B72')
ax1.plot(thresholds, metrics_by_threshold['Precision'], label='Precision', linewidth=2.5, color='#F18F01')
ax1.plot(thresholds, metrics_by_threshold['Accuracy'], label='Accuracy', linewidth=2.5, color='#C73E1D')
# Mark optimal F1 threshold
ax1.axvline(optimal_f1_threshold, color='green', linestyle='--', linewidth=2, alpha=0.7, label=f'Optimal F1 (threshold={optimal_f1_threshold:.2f})')
ax1.set_xlabel('Decision Threshold', fontsize=11)
ax1.set_ylabel('Metric Value', fontsize=11)
ax1.set_title('Performance Metrics Across Decision Thresholds', fontsize=13, fontweight='bold')
ax1.legend(loc='best', fontsize=10)
ax1.grid(True, alpha=0.3)
ax1.set_xlim([0, 1])
ax1.set_ylim([0, 1.05])
# Panel 2: F1 Score and Youden's J
ax2.plot(thresholds, metrics_by_threshold['F1_Score'], label='F1 Score', linewidth=2.5, color='#06A77D')
ax2.plot(thresholds, youden_j, label="Youden's J (Sensitivity + Specificity - 1)", linewidth=2.5, color='#D62828')
# Mark optimal points
ax2.scatter([optimal_f1_threshold], [optimal_f1_value], color='green', s=100, zorder=5, edgecolors='darkgreen', linewidth=2, label=f'Max F1: {optimal_f1_value:.4f}')
ax2.scatter([optimal_j_threshold], [optimal_j_value], color='red', s=100, zorder=5, edgecolors='darkred', linewidth=2, label=f"Max J: {optimal_j_value:.4f}")
# Mark default 0.5 threshold
ax2.axvline(0.5, color='gray', linestyle=':', linewidth=2, alpha=0.6, label='Default threshold (0.5)')
ax2.set_xlabel('Decision Threshold', fontsize=11)
ax2.set_ylabel('Metric Value', fontsize=11)
ax2.set_title('Optimization Metrics: F1 Score and Youden\'s J Statistic', fontsize=13, fontweight='bold')
ax2.legend(loc='best', fontsize=10)
ax2.grid(True, alpha=0.3)
ax2.set_xlim([0, 1])
ax2.set_ylim([-0.1, 1.05])
plt.tight_layout()
plt.savefig(output_path, dpi=150, bbox_inches='tight')
plt.close()
print(f" ✓ Threshold analysis saved: {output_path}")
print(f" - Optimal F1 threshold: {optimal_f1_threshold:.3f} (F1={optimal_f1_value:.4f})")
print(f" - Optimal Youden threshold: {optimal_j_threshold:.3f} (J={optimal_j_value:.4f})")
def plot_ensemble_roc_pr_curves(all_labels, ensemble_mean_prob, ensemble_max_prob, output_path, figsize=(16, 6)):
"""
Plot ensemble voting ROC and PR curves with multiple probability aggregation methods.
Shows model performance across all decision thresholds using:
- ROC Curve: Plots TPR vs FPR (sensitivity vs false positive rate)
- PR Curve: Plots Precision vs Recall (positive predictive value vs sensitivity)
Compares two ensemble probability aggregation methods:
- Mean Ensemble Probability: Average prediction confidence across 5 folds
- Max Ensemble Probability: Maximum prediction confidence across 5 folds
Args:
all_labels: True labels (binary, 0/1)
ensemble_mean_prob: Mean probability from ensemble (for each patient)
ensemble_max_prob: Max probability from ensemble (for each patient)
output_path: Path to save PNG file
figsize: Figure size tuple (width, height)
"""
# Calculate metrics for both probability aggregation methods
fpr_mean, tpr_mean, _ = roc_curve(all_labels, ensemble_mean_prob)
roc_auc_mean = auc(fpr_mean, tpr_mean)
fpr_max, tpr_max, _ = roc_curve(all_labels, ensemble_max_prob)
roc_auc_max = auc(fpr_max, tpr_max)
precision_mean, recall_mean, _ = precision_recall_curve(all_labels, ensemble_mean_prob)
pr_auc_mean = average_precision_score(all_labels, ensemble_mean_prob)
precision_max, recall_max, _ = precision_recall_curve(all_labels, ensemble_max_prob)
pr_auc_max = average_precision_score(all_labels, ensemble_max_prob)
# Create side-by-side subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize)
# ========== ROC CURVE PANEL ==========
# ROC: TPR (sensitivity) vs FPR (1-specificity)
ax1.plot(fpr_mean, tpr_mean, color='#2E86AB', lw=3, label=f'Mean Prob (AUC = {roc_auc_mean:.4f})')
ax1.plot(fpr_max, tpr_max, color='#A23B72', lw=3, linestyle='--', label=f'Max Prob (AUC = {roc_auc_max:.4f})')
ax1.plot([0, 1], [0, 1], color='red', lw=2, linestyle=':', alpha=0.6, label='Random Classifier')
ax1.set_xlabel('False Positive Rate (1 - Specificity)', fontsize=12, fontweight='bold')
ax1.set_ylabel('True Positive Rate (Sensitivity)', fontsize=12, fontweight='bold')
ax1.set_title('Ensemble ROC Curves\n(Probability aggregation comparison)', fontsize=13, fontweight='bold')
ax1.legend(loc='lower right', fontsize=11)
ax1.grid(True, alpha=0.3)
ax1.set_xlim([0.0, 1.0])
ax1.set_ylim([0.0, 1.05])
# Add diagonal reference
ax1.fill_between([0, 1], 0, 1, alpha=0.1, color='gray')
# ========== PRECISION-RECALL CURVE PANEL ==========
# PR: Precision (PPV) vs Recall (Sensitivity)
ax2.plot(recall_mean, precision_mean, color='#06A77D', lw=3, label=f'Mean Prob (AP = {pr_auc_mean:.4f})')
ax2.plot(recall_max, precision_max, color='#F18F01', lw=3, linestyle='--', label=f'Max Prob (AP = {pr_auc_max:.4f})')
# Add reference: no-skill classifier (proportion of positives)
baseline = np.sum(all_labels == 1) / len(all_labels)
ax2.axhline(y=baseline, color='red', lw=2, linestyle=':', alpha=0.6, label=f'Random Classifier (P={baseline:.3f})')
ax2.set_xlabel('Recall (Sensitivity = TP/(TP+FN))', fontsize=12, fontweight='bold')
ax2.set_ylabel('Precision (PPV = TP/(TP+FP))', fontsize=12, fontweight='bold')
ax2.set_title('Ensemble Precision-Recall Curves\n(Probability aggregation comparison)', fontsize=13, fontweight='bold')
ax2.legend(loc='best', fontsize=11)
ax2.grid(True, alpha=0.3)
ax2.set_xlim([0.0, 1.0])
ax2.set_ylim([0.0, 1.05])
# Add shaded region for ideal performance
ax2.fill_between([0, 1], 1, 0, alpha=0.05, color='green')
plt.tight_layout()
plt.savefig(output_path, dpi=150, bbox_inches='tight')
plt.close()
print(f" ✓ Ensemble ROC/PR curves saved: {output_path}")
print(f" - ROC-AUC (Mean Prob): {roc_auc_mean:.4f}")
print(f" - ROC-AUC (Max Prob): {roc_auc_max:.4f}")
print(f" - PR-AUC (Mean Prob): {pr_auc_mean:.4f}")
print(f" - PR-AUC (Max Prob): {pr_auc_mean:.4f}")
# ============================================================================
# BOOTSTRAP CONFIDENCE INTERVAL VISUALIZATION
# ============================================================================
def plot_bootstrap_confidence_intervals(bootstrap_ci_csv, output_path, figsize=(16, 8)):
"""
Visualize bootstrap confidence intervals as error bars for key metrics.
Args:
bootstrap_ci_csv: Path to CSV file with bootstrap CI results
(from ensemble_voting or meta_classifier)
output_path: Path to save PNG file
figsize: Figure size (width, height)
Output: Publication-ready PNG with error bars showing metric uncertainty
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Load bootstrap CI data
df = pd.read_csv(bootstrap_ci_csv)
# Select key metrics for visualization
key_metrics = [
"Recall", "Precision", "Accuracy", "F1_Score",
"Sensitivity", "Specificity", "Balanced_Accuracy",
"PPV_(Positive_Predictive_Value)",
"Matthews_Correlation_Coefficient"
]
# Filter to only available metrics in CSV
available_metrics = [m for m in key_metrics if m in df['Metric'].values]
df_plot = df[df['Metric'].isin(available_metrics)].copy()
df_plot = df_plot.reset_index(drop=True)
# Extract data for plotting
metrics = df_plot['Metric'].values
point_estimates = df_plot['Point_Estimate'].values
ci_lower = df_plot['CI_Lower_95%'].values
ci_upper = df_plot['CI_Upper_95%'].values
# Calculate error margins
error_lower = point_estimates - ci_lower
error_upper = ci_upper - point_estimates
errors = np.array([error_lower, error_upper])
# Create figure
fig, ax = plt.subplots(figsize=figsize)
# Color palette for metrics
colors = plt.cm.Set3(np.linspace(0, 1, len(metrics)))
# Plot horizontal error bars
y_positions = np.arange(len(metrics))
ax.barh(y_positions, point_estimates, xerr=errors,
color=colors, alpha=0.75, capsize=8,
error_kw={'elinewidth': 3, 'capthick': 2})
# Customize plot
ax.set_yticks(y_positions)
ax.set_yticklabels(metrics, fontsize=11, fontweight='bold')
ax.set_xlabel('Metric Value', fontsize=13, fontweight='bold')
ax.set_title('Bootstrap Confidence Intervals (95% CI)\nError Bars Show Uncertainty from 1000 Resamples',
fontsize=14, fontweight='bold', pad=20)
# Add grid for readability
ax.grid(axis='x', alpha=0.3, linestyle='--')
ax.set_xlim(0, 1.05)
# Add value labels on bars
for i, (estimate, ci_l, ci_u) in enumerate(zip(point_estimates, ci_lower, ci_upper)):
ax.text(estimate + 0.02, i, f'{estimate:.4f}\n[{ci_l:.4f}-{ci_u:.4f}]',
va='center', fontsize=9, fontweight='bold')
plt.tight_layout()
plt.savefig(output_path, dpi=300, bbox_inches='tight', facecolor='white')
plt.close()
return output_path
# ============================================================================
# GRAD-CAM VISUALIZATION
# ============================================================================
def plot_gradcam_pair(patch_img, heatmap, patient_id, rank, patch_idx,
attention_score, prob, is_false_negative=False,
is_false_positive=False, output_dir=None):
"""
Create side-by-side visualization of patch and Grad-CAM heatmap.
Args:
patch_img: Original patch tensor (1, C, H, W) or (C, H, W)
heatmap: Normalized saliency heatmap (H, W) in [0, 1]
patient_id: Patient identifier string
rank: Rank among top patches (0, 1, 2, ...)
patch_idx: Patch index within patient bag
attention_score: Attention weight for this patch
prob: Model's positive class probability
is_false_negative: Whether this is a false negative (ghost patient)
is_false_positive: Whether this is a false positive (artifact)
output_dir: Directory to save PNG file
Returns:
output_path: Path to saved PNG file
"""
# Handle tensor reshaping
if len(patch_img.shape) == 4:
patch_img = patch_img[0] # (C, H, W)
# Convert to numpy and denormalize (ImageNet stats)
orig_img = patch_img.cpu().permute(1, 2, 0).numpy()
orig_img = orig_img * np.array([0.229, 0.224, 0.225]) + np.array([0.485, 0.456, 0.406])
orig_img = np.clip(orig_img, 0, 1)
# Create side-by-side figure
plt.figure(figsize=(10, 5))
# Left: Original image
plt.subplot(1, 2, 1)
plt.imshow(orig_img)
plt.title(f"Patch {patch_idx} (Attn: {attention_score:.4f})")
plt.axis('off')
# Right: Heatmap overlay
plt.subplot(1, 2, 2)
plt.imshow(orig_img)
plt.imshow(heatmap, cmap='jet', alpha=0.6)
if is_false_negative:
prefix = "FN_"
title_prefix = "FN (Ghost) "
elif is_false_positive:
prefix = "FP_"
title_prefix = "FP (Artifact) "
else:
prefix = ""
title_prefix = ""
plt.title(f"{title_prefix}Grad-CAM (Prob: {prob:.4f})")
plt.axis('off')
# Save
if output_dir is None:
output_dir = "results"
os.makedirs(output_dir, exist_ok=True)
if is_false_negative or is_false_positive:
out_path = os.path.join(output_dir, f"{prefix}{patient_id}_rank{rank}_patch{patch_idx}.png")
else:
out_path = os.path.join(output_dir, f"{patient_id}_rank{rank}_patch{patch_idx}.png")
plt.savefig(out_path, bbox_inches='tight')
plt.close()
return out_path
# ============================================================================
# NEW ADVANCED VISUALIZATIONS FOR REPORTS & PRESENTATIONS
# ============================================================================
def plot_calibration_curve(all_labels, all_probs, output_path, figsize=(10, 8), num_bins=10):
"""
Plot model calibration: Predicted probability vs actual positive rate.
A well-calibrated model has predictions that match reality. This plot shows
if the model's confidence estimates are reliable for clinical decision-making.
If the curve lies above the diagonal: model is underconfident (predicts low probability
for positive cases). Below: model is overconfident.
Args:
all_labels: True labels (binary, 0/1)
all_probs: Predicted probabilities [0, 1]
output_path: Path to save PNG file
figsize: Figure size (width, height)
num_bins: Number of bins for calibration curve
Output: Calibration plot showing reliability of confidence estimates
"""
# Bin predictions
bin_edges = np.linspace(0, 1, num_bins + 1)
bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2
bin_sums = np.zeros(num_bins)
bin_true = np.zeros(num_bins)
bin_total = np.zeros(num_bins)
for prob, label in zip(all_probs, all_labels):
bin_idx = min(int(prob * num_bins), num_bins - 1)
bin_sums[bin_idx] += prob
bin_true[bin_idx] += label
bin_total[bin_idx] += 1
# Calculate empirical probabilities
nonzero = bin_total > 0
bin_centers_nonzero = bin_centers[nonzero]
empirical_prob = bin_true[nonzero] / bin_total[nonzero]
predicted_prob = bin_sums[nonzero] / bin_total[nonzero]
# Expected Calibration Error (ECE)
ece = np.mean(np.abs(predicted_prob - empirical_prob))
# Create figure
fig, ax = plt.subplots(figsize=figsize)
# Plot calibration curve
ax.plot(predicted_prob, empirical_prob, 'o-', linewidth=3, markersize=8,
label='Model Predictions', color='#2E86AB')
# Perfect calibration line
ax.plot([0, 1], [0, 1], 'k--', linewidth=2, alpha=0.6, label='Perfect Calibration')
# Shaded regions for over/under confidence
ax.fill_between([0, 1], [0, 1], [1, 1], alpha=0.1, color='red', label='Overconfident Region')
ax.fill_between([0, 1], [0, 1], [0, 0], alpha=0.1, color='green', label='Underconfident Region')
# Customize
ax.set_xlabel('Mean Predicted Probability', fontsize=12, fontweight='bold')
ax.set_ylabel('Fraction of Positives (True Probability)', fontsize=12, fontweight='bold')
ax.set_title(f'Model Calibration Curve\n(Expected Calibration Error = {ece:.4f})',
fontsize=13, fontweight='bold')
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
ax.grid(True, alpha=0.3)
ax.legend(loc='upper left', fontsize=11)
# Add diagonal line from origin to top-right
ax.set_aspect('equal')
plt.tight_layout()
plt.savefig(output_path, dpi=150, bbox_inches='tight')
plt.close()
print(f" ✓ Calibration curve saved: {output_path}")
print(f" - Expected Calibration Error (ECE): {ece:.4f}")
def plot_patient_performance_dashboard(all_labels, all_preds, all_probs,
fold_metrics, bootstrap_ci, roc_auc, pr_auc,
output_path, figsize=(16, 12)):
"""
Create comprehensive 4-panel performance dashboard for clinical presentation.
Combines confusion matrix, ROC curve, PR curve, and performance metrics
in a single publication-ready figure.
Args:
all_labels: True labels (binary)
all_preds: Binary predictions (0/1)
all_probs: Predicted probabilities
fold_metrics: Dict with computed metrics (sensitivity, specificity, etc.)
bootstrap_ci: Dict with bootstrap CI data
roc_auc: ROC-AUC score
pr_auc: PR-AUC score
output_path: Path to save PNG file
figsize: Figure size (width, height)
Output: 4-panel dashboard with confusion matrix, ROC, PR curves, and metrics table
"""
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
# Create 2x2 grid
fig = plt.figure(figsize=figsize)
gs = fig.add_gridspec(2, 2, hspace=0.35, wspace=0.3)
# ========== PANEL 1: CONFUSION MATRIX ==========
ax1 = fig.add_subplot(gs[0, 0])
cm = confusion_matrix(all_labels, all_preds)
disp = ConfusionMatrixDisplay(cm, display_labels=['Negative', 'Positive'])
disp.plot(cmap='Blues', ax=ax1, values_format='d')
ax1.set_title('Confusion Matrix (Patient-Level)', fontsize=12, fontweight='bold')