-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhist_metrics.py
2074 lines (1405 loc) · 70.7 KB
/
hist_metrics.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["SM_FRAMEWORK"] = "tf.keras"
import segmentation_models as sm
import tensorflow as tf
import numpy as np
import cupy as cp
import cupyx.scipy.ndimage
from cupyx.scipy.spatial.distance import cdist
# from scipy.spatial.distance import cdist
import random
import pandas as pd
import shutil
from tqdm import tqdm
import cv2
import matplotlib.pyplot as plt
from patchify import patchify, unpatchify
import subprocess
import time
import datetime
import seg_metrics.seg_metrics as sg
from medpy.metric.binary import dc as mpdc
from medpy.metric.binary import jc as mpjc
from medpy.metric.binary import hd as mphd
from medpy.metric.binary import asd as mpasd
from medpy.metric.binary import specificity as mpspecificity
from medpy.metric.binary import sensitivity as mpsensitivity
from medpy.metric.binary import precision as mpprecision
from medpy.metric.binary import recall as mprecall
seed = 13334
np.random.seed(seed)
random.seed(seed)
tf.random.set_seed(seed)
tf.keras.utils.set_random_seed(seed)
cp.random.seed(seed=seed)
def conf_matrix_keras_iou_manual(y_test, pred):
m = tf.keras.metrics.BinaryIoU()
m.reset_state()
m.update_state(y_test, pred)
print("----------------------------------")
values = np.array(m.get_weights()).reshape(2,2)
print(values)
print("Keras mIoU: ", m.result().numpy() )
#IOU for each class is..
# IOU = true_positive / (true_positive + false_positive + false_negative).
conf_matrix = values
# To calculate IoU for each class
values = conf_matrix
class0_iou = values[0, 0] / (values[0, 0] + values[0, 1] + values[1, 0])
class1_iou = values[1, 1] / (values[1, 1] + values[1, 0] + values[0, 1])
print("IoU for Class 0:", class0_iou)
print("IoU for Class 1:", class1_iou)
def miou_keras_class_0(y_test, pred, threshold):
m = tf.keras.metrics.BinaryIoU(target_class_ids=[0], threshold=threshold)
m.reset_state()
m.update_state(y_test, pred)
return m.result().numpy()
def miou_keras_class_1(y_test, pred, threshold):
m = tf.keras.metrics.BinaryIoU(target_class_ids=[1], threshold=threshold)
m.reset_state()
m.update_state(y_test, pred)
return m.result().numpy()
def keras_bin_miou_per_image(y_test, pred):
def iou_keras_def(mask1, mask2):
m = tf.keras.metrics.BinaryIoU(target_class_ids=[1])
m.reset_state()
m.update_state(mask1, mask2)
iou = m.result().numpy()
return iou
iou_score_each_sample = []
for i in range(0, y_test.shape[0]):
d = iou_keras_def(y_test[i], pred[i])
iou_score_each_sample.append(d)
return np.mean(iou_score_each_sample)
# def np_miou_per_image(y_test, pred):
# def calculateIoU(gtMask, predMask):
# predMask = (predMask > 0.5)
# predMask = np.where(predMask>0, 1, 0)
# # Calculate the true positives,
# # false positives, and false negatives
# tp = 0
# fp = 0
# fn = 0
# for i in range(len(gtMask)):
# for j in range(len(gtMask[0])):
# if gtMask[i][j] == 1 and predMask[i][j] == 1:
# tp += 1
# elif gtMask[i][j] == 0 and predMask[i][j] == 1:
# fp += 1
# elif gtMask[i][j] == 1 and predMask[i][j] == 0:
# fn += 1
# # Calculate IoU
# iou = tp / (tp + fp + fn)
# return iou
# iou_score_each_sample = []
# for i in range(0, y_test.shape[0]):
# d = calculateIoU(y_test[i], pred[i])
# iou_score_each_sample.append(d)
# return np.mean(iou_score_each_sample)
def calculateIoU(gtMask, predMask):
"""Calculate IoU for a single image using Cupy."""
# predMask = cp.where(predMask > threshold, 1, 0)
tp = cp.sum((gtMask == 1) & (predMask == 1))
fp = cp.sum((gtMask == 0) & (predMask == 1))
fn = cp.sum((gtMask == 1) & (predMask == 0))
iou = tp / (tp + fp + fn)
return iou
def np_miou_per_image(y_test, pred):
y_test = cp.asarray(y_test)
pred = cp.asarray(pred)
"""Compute mean IoU per image over a batch using Cupy."""
iou_scores = cp.zeros(y_test.shape[0], dtype=cp.float32)
for i in range(y_test.shape[0]):
iou_scores[i] = calculateIoU(y_test[i], pred[i])
result = cp.mean(iou_scores).get() # Convert to NumPy for compatibility if needed
result = result.astype(np.float32).item()
return round(result,4)
# def np_dice_per_image(y_test, pred):
# pred = (pred > 0.5)
# pred = np.where(pred>0, 1, 0)
# def DICE_COE(mask1, mask2):
# intersect = np.sum(mask1*mask2)
# fsum = np.sum(mask1)
# ssum = np.sum(mask2)
# dice = (2 * intersect ) / (fsum + ssum)
# #dice = np.mean(dice)
# #dice = round(dice, 2) # for easy reading
# return dice
# dice_score_each_sample = []
# for i in range(0, y_test.shape[0]):
# d = DICE_COE(y_test[i], pred[i])
# dice_score_each_sample.append(d)
# return np.mean(dice_score_each_sample)
def DICE_COE(mask1, mask2):
"""Calculate Dice coefficient for a single image using Cupy."""
intersect = cp.sum(mask1 * mask2)
fsum = cp.sum(mask1)
ssum = cp.sum(mask2)
dice = (2. * intersect) / (fsum + ssum)
return dice
def np_dice_per_image(y_test, pred):
y_test = cp.asarray(y_test)
pred = cp.asarray(pred)
"""Compute mean Dice coefficient per image over a batch using Cupy."""
dice_scores = cp.zeros(y_test.shape[0], dtype=cp.float32)
for i in range(y_test.shape[0]):
dice_scores[i] = DICE_COE(y_test[i], pred[i])
result = cp.mean(dice_scores).get()
result = result.astype(np.float32).item()
return round(result,4)
def calculateHD(gtMask, predMask):
"""
Calculate the Hausdorff Distance (HD) for a single image using CuPy.
"""
gtBoundary = cp.argwhere(gtMask)
predBoundary = cp.argwhere(predMask)
if len(gtBoundary) == 0 or len(predBoundary) == 0:
return cp.inf
distances = cdist(gtBoundary, predBoundary, metric='euclidean')
max_dist_gt_to_pred = cp.max(cp.min(distances, axis=1))
max_dist_pred_to_gt = cp.max(cp.min(distances, axis=0))
hd = cp.max(cp.array([max_dist_gt_to_pred, max_dist_pred_to_gt]))
return hd.get()
def np_hd_per_image(y_test, pred):
"""
Compute Hausdorff Distance (HD) per image over a batch using CuPy.
"""
# Ensure the input arrays are CuPy arrays
y_test_cp = cp.asarray(y_test)
pred_cp = cp.asarray(pred)
hd_scores = cp.zeros(y_test_cp.shape[0], dtype=cp.float64)
for i in range(y_test_cp.shape[0]):
hd_scores[i] = calculateHD(y_test_cp[i], pred_cp[i])
valid_scores = hd_scores[cp.isfinite(hd_scores)]
if len(valid_scores) == 0:
return float('inf')
mean_hd = cp.mean(valid_scores).get() # Convert to Python float for compatibility
# return mean_hd[0]
return round(mean_hd.item(), 4)
def sm_iou_score_per_image(y_test, pred, threshold):
sm_iou = sm.metrics.IOUScore(per_image = True, threshold = threshold)
return sm_iou(y_test, pred).numpy()
def sm_iou_score_whole_batch(y_test, pred, threshold):
sm_iou = sm.metrics.IOUScore(per_image = False, threshold = threshold)
return sm_iou(y_test, pred).numpy()
def sm_f1_score_per_image(y_test, pred, threshold):
sm_f1 = sm.metrics.FScore(per_image = True, threshold = threshold)
return sm_f1(y_test, pred).numpy()
def sm_f1_score_whole_batch(y_test, pred, threshold):
sm_f1 = sm.metrics.FScore(per_image = False, threshold = threshold)
return sm_f1(y_test, pred).numpy()
def sm_precision_whole_batch(y_test, pred, threshold):
sm_precision = sm.metrics.Precision(per_image = False, threshold = threshold)
return sm_precision(y_test, pred).numpy()
def sm_precision_per_image(y_test, pred, threshold):
sm_precision = sm.metrics.Precision(per_image = True, threshold = threshold)
return sm_precision(y_test, pred).numpy()
def sm_recall_whole_batch(y_test, pred, threshold):
sm_recall = sm.metrics.Recall(per_image = False, threshold = threshold)
return sm_recall(y_test, pred).numpy()
def sm_recall_per_image(y_test, pred, threshold):
sm_recall = sm.metrics.Recall(per_image = True, threshold = threshold)
return sm_recall(y_test, pred).numpy()
def medpy_dice(y_test, pred):
results_mpdc = mpdc(y_test, pred)
return results_mpdc
def medpy_jc(y_test, pred):
results_mpjc = mpjc(y_test, pred)
return results_mpjc
def medpy_hd(y_test, pred):
results_mphd = mphd(y_test, pred)
return results_mphd
def medpy_asd(y_test, pred):
results_mpasd = mpasd(y_test, pred)
return results_mpasd
def medpy_specificity(y_test, pred):
results_mpspecificity = mpspecificity(y_test, pred)
return results_mpspecificity
def medpy_sensitivity(y_test, pred):
results_mpsensitivity = mpsensitivity(y_test, pred)
return results_mpsensitivity
def medpy_precision(y_test, pred):
results_mpprecision= mpprecision(y_test, pred)
return results_mpprecision
def medpy_recall(y_test, pred):
results_mprecall= mprecall(y_test, pred)
return results_mprecall
def np_p_r_f1(y_test, pred):
def calculate_metrics_per_image(y_true, y_pred):
num_images = y_true.shape[0]
total_precision, total_recall, total_f1_score = 0, 0, 0
for i in range(num_images):
# Flatten the arrays for the i-th image
y_true_flatten = y_true[i].flatten()
y_pred_flatten = y_pred[i].flatten()
# True Positives, False Positives, False Negatives, True Negatives
tp = np.sum((y_true_flatten == 1) & (y_pred_flatten == 1))
fp = np.sum((y_true_flatten == 0) & (y_pred_flatten == 1))
fn = np.sum((y_true_flatten == 1) & (y_pred_flatten == 0))
# Precision, Recall, F1 Score for the i-th image
precision = tp / (tp + fp) if (tp + fp) > 0 else 0
recall = tp / (tp + fn) if (tp + fn) > 0 else 0
f1_score = 2 * (precision * recall) / (precision + recall) if (precision + recall) > 0 else 0
total_precision += precision
total_recall += recall
total_f1_score += f1_score
# Calculate average metrics
avg_precision = total_precision / num_images
avg_recall = total_recall / num_images
avg_f1_score = total_f1_score / num_images
return avg_precision, avg_recall, avg_f1_score
return calculate_metrics_per_image(y_test, pred)
def np_specificity_np_sensitivity(y_test, pred):
def calculate_average_sensitivity_specificity(y_test, pred):
total_sensitivity = 0
total_specificity = 0
num_images = y_test.shape[0]
for i in range(num_images):
y_test_flat = y_test[i].flatten()
pred_flat = pred[i].flatten()
# Calculating True Positives, False Positives, True Negatives, and False Negatives
TP = np.sum((y_test_flat == 1) & (pred_flat == 1))
FP = np.sum((y_test_flat == 0) & (pred_flat == 1))
TN = np.sum((y_test_flat == 0) & (pred_flat == 0))
FN = np.sum((y_test_flat == 1) & (pred_flat == 0))
# Calculating Sensitivity and Specificity for each image
sensitivity = TP / (TP + FN) if (TP + FN) != 0 else 0
specificity = TN / (TN + FP) if (TN + FP) != 0 else 0
total_sensitivity += sensitivity
total_specificity += specificity
# Calculating average sensitivity and specificity
average_sensitivity = total_sensitivity / num_images
average_specificity = total_specificity / num_images
return average_sensitivity, average_specificity
# Example usage
average_sensitivity, average_specificity = calculate_average_sensitivity_specificity(y_test, pred)
# print("Average Sensitivity:", average_sensitivity)
# print("Average Specificity:", average_specificity)
return [average_specificity, average_sensitivity]
def np_object_p_r_f2(y_test, pred, iou_threshold):
def label_objects_cupy(segmentation_map):
"""
Label individual objects in a binary segmentation map using Cupyx.
"""
labeled_map, num_features = cupyx.scipy.ndimage.label(segmentation_map)
return labeled_map, num_features
def calculate_iou_cupy(predicted_map, ground_truth_map, predicted_label, ground_truth_label):
"""
Calculate the Intersection over Union (IoU) for a predicted object and a ground truth object.
"""
predicted_object = (predicted_map == predicted_label)
ground_truth_object = (ground_truth_map == ground_truth_label)
intersection = cp.logical_and(predicted_object, ground_truth_object).sum()
union = cp.logical_or(predicted_object, ground_truth_object).sum()
return intersection / union if union != 0 else 0
def match_objects(predicted_map, ground_truth_map, iou_threshold):
"""
Match predicted objects to ground truth objects based on IoU threshold.
"""
predicted_labels = cp.unique(predicted_map)[1:] # Exclude background
ground_truth_labels = cp.unique(ground_truth_map)[1:] # Exclude background
matches = []
unmatched_predicted = {int(label) for label in predicted_labels.tolist()} # Convert to set of integers
unmatched_ground_truth = {int(label) for label in ground_truth_labels.tolist()} # Convert to set of integers
for p_label in predicted_labels:
best_match = None
best_iou = iou_threshold
for gt_label in ground_truth_labels:
iou = calculate_iou_cupy(predicted_map, ground_truth_map, int(p_label), int(gt_label))
if iou > best_iou:
best_match = (int(p_label), int(gt_label))
best_iou = iou
if best_match:
matches.append(best_match)
unmatched_predicted.discard(best_match[0])
unmatched_ground_truth.discard(best_match[1])
return matches, unmatched_predicted, unmatched_ground_truth
def calculate_metrics_for_batch(y_test, pred, iou_threshold):
"""
Calculate object-level precision, recall, and F1 score for a batch of images.
"""
batch_size = pred.shape[0]
precision_list = []
recall_list = []
f1_score_list = []
for i in range(batch_size):
predicted_map = cp.asarray(pred[i, ..., 0]) # Convert to Cupy array and remove channel dimension
ground_truth_map = cp.asarray(y_test[i, ..., 0]) # Convert to Cupy array and remove channel dimension
predicted_labeled_map, _ = label_objects_cupy(predicted_map)
ground_truth_labeled_map, _ = label_objects_cupy(ground_truth_map)
matches, unmatched_predicted, unmatched_ground_truth = match_objects(predicted_labeled_map, ground_truth_labeled_map, iou_threshold)
tp = len(matches)
fp = len(unmatched_predicted)
fn = len(unmatched_ground_truth)
precision = tp / (tp + fp) if (tp + fp) > 0 else 0
recall = tp / (tp + fn) if (tp + fn) > 0 else 0
f1_score = 2 * (precision * recall) / (precision + recall) if (precision + recall) > 0 else 0
precision_list.append(precision)
recall_list.append(recall)
f1_score_list.append(f1_score)
# Calculate average metrics across the batch
avg_precision = np.mean(precision_list)
avg_recall = np.mean(recall_list)
avg_f1_score = np.mean(f1_score_list)
return avg_precision, avg_recall, avg_f1_score
avg_precision, avg_recall, avg_f1_score = calculate_metrics_for_batch(y_test, pred, iou_threshold)
return [avg_precision, avg_recall, avg_f1_score]
def seg_metrics_fuc(y_test, pred):
dice_arr = []
jaccard_arr = []
precision_arr = []
recall_arr = []
fpr_arr = []
fnr_arr = []
vs_arr = []
hd_arr = []
hd95_arr = []
msd_arr = []
mdsd_arr = []
stdsd_arr = []
tp_arr = []
tn_arr = []
fp_arr = []
fn_arr = []
false_omission_rate_arr = []
accuracy_arr = []
for i in range(y_test.shape[0]):
gdth_img = y_test[i]
pred_img = pred[i]
labels = [1]
csv_file = 'metrics.csv'
metrics = sg.write_metrics(labels=labels, # exclude background if needed
gdth_img=gdth_img,
pred_img=pred_img,
TPTNFPFN=True,
metrics=['dice','jaccard','precision','recall','fpr','fnr','vs','hd','hd95','msd','mdsd','stdsd','TP','TN','FP','FN'])
metrics = metrics[0]
metrics = {k: float(v[0]) for k, v in metrics.items()}
# print(metrics)
dice, jaccard, precision, recall ,fpr ,fnr ,vs ,hd ,hd95 ,msd ,mdsd ,stdsd , tp, tn, fp, fn = metrics['dice'], metrics['jaccard'], metrics['precision'], metrics['recall'], metrics['fpr'], metrics['fnr'], metrics['vs'], metrics['hd'], metrics['hd95'], metrics['msd'], metrics['mdsd'], metrics['stdsd'], metrics['TP'] , metrics['TN'] , metrics['FP'] , metrics['FN']
false_omission_rate = fn/(fn+tn)
accuracy = (tp + tn)/(tp + tn + fp + fn)
# print(false_omission_rate)
# print(accuracy)
dice_arr.append(dice)
jaccard_arr.append(jaccard)
precision_arr.append(precision)
recall_arr.append(recall)
fpr_arr.append(fpr)
fnr_arr.append(fnr)
vs_arr.append(vs)
hd_arr.append(hd)
hd95_arr.append(hd95)
msd_arr.append(msd)
mdsd_arr.append(mdsd)
stdsd_arr.append(stdsd)
tp_arr.append(tp)
tn_arr.append(tn)
fp_arr.append(fp)
fn_arr.append(fn)
false_omission_rate_arr.append(false_omission_rate)
accuracy_arr.append(accuracy)
total_n = y_test.shape[0]
dice_arr = np.array(dice_arr).mean()
jaccard_arr = np.array(jaccard_arr).mean()
precision_arr = np.array(precision_arr).mean()
recall_arr = np.array(recall_arr).mean()
fpr_arr = np.array(fpr_arr).mean()
fnr_arr = np.array(fnr_arr).mean()
vs_arr = np.array(vs_arr).mean()
hd_arr = np.array(hd_arr).mean()
hd95_arr = np.array(hd95_arr).mean()
msd_arr = np.array(msd_arr).mean()
mdsd_arr = np.array(mdsd_arr).mean()
stdsd_arr = np.array(stdsd_arr).mean()
tp_arr = np.array(tp_arr).mean()
tn_arr = np.array(tn_arr).mean()
fp_arr = np.array(fp_arr).mean()
fn_arr = np.array(fn_arr).mean()
false_omission_rate_arr = np.array(false_omission_rate_arr).mean()
accuracy_arr = np.array(accuracy_arr).mean()
return dice_arr, jaccard_arr, precision_arr, recall_arr, fpr_arr, fnr_arr, vs_arr, hd_arr, hd95_arr, msd_arr, mdsd_arr, stdsd_arr, tp_arr, tn_arr, fp_arr, fn_arr, false_omission_rate_arr, accuracy_arr
def eval_all_metrics(y_test, pred, all = 0, threshold_pred = 0.5):
pred = np.where(pred>threshold_pred, 1, 0)
pred = pred.astype(np.float32)
df = pd.DataFrame(columns=['Metric', 'Score'])
try:
record = {'Metric': "miou_keras_class_0", 'Score': miou_keras_class_0(y_test, pred, threshold_pred)}
except:
record = {'Metric': "miou_keras_class_0", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
try:
record = {'Metric': "miou_keras_class_1", 'Score': miou_keras_class_1(y_test, pred, threshold_pred)}
except:
record = {'Metric': "miou_keras_class_1", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
try:
record = {'Metric': "sm_iou_score_whole_batch", 'Score': sm_iou_score_whole_batch(y_test, pred, threshold_pred)}
except:
record = {'Metric': "sm_iou_score_whole_batch", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "medpy_jc", 'Score': medpy_jc(y_test, pred)}
except:
record = {'Metric': "medpy_jc", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
try:
record = {'Metric': "keras_bin_miou_per_image", 'Score': keras_bin_miou_per_image(y_test, pred)}
except:
record = {'Metric': "keras_bin_miou_per_image", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
try:
record = {'Metric': "sm_iou_score_per_image", 'Score': sm_iou_score_per_image(y_test, pred, threshold_pred)}
except:
record = {'Metric': "sm_iou_score_per_image", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "np_miou_per_image", 'Score': np_miou_per_image(y_test, pred)}
except:
record = {'Metric': "np_miou_per_image", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "np_dice_per_image", 'Score': np_dice_per_image(y_test, pred)}
except:
record = {'Metric': "np_dice_per_image", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "sm_f1_score_per_image", 'Score': sm_f1_score_per_image(y_test, pred, threshold_pred)}
except:
record = {'Metric': "sm_f1_score_per_image", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "np_f1_score_per_image", 'Score': np_p_r_f1(y_test, pred)[2]}
except:
record = {'Metric': "np_f1_score_per_image", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "sm_f1_score_whole_batch", 'Score': sm_f1_score_whole_batch(y_test, pred, threshold_pred)}
except:
record = {'Metric': "sm_f1_score_whole_batch", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "medpy_dice", 'Score': medpy_dice(y_test, pred)}
except:
record = {'Metric': "medpy_dice", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "medpy_hd", 'Score': medpy_hd(y_test, pred)}
except:
record = {'Metric': "medpy_hd", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
# if all == 1:
# try:
# record = {'Metric': "np_hd_per_image", 'Score': np_hd_per_image(y_test, pred)}
# except:
# record = {'Metric': "np_hd_per_image", 'Score': -1}
# df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "medpy_asd", 'Score': medpy_asd(y_test, pred)}
except:
record = {'Metric': "medpy_asd", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
# record = {'Metric': "medpy_specificity", 'Score': medpy_specificity(y_test, pred)}
# df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
# record = {'Metric': "medpy_sensitivity", 'Score': medpy_sensitivity(y_test, pred)}
# df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
# record = {'Metric': "medpy_precision", 'Score': medpy_precision(y_test, pred)}
# df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
# record = {'Metric': "medpy_recall", 'Score': medpy_recall(y_test, pred)}
# df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "sm_precision_whole_batch", 'Score': sm_precision_whole_batch(y_test, pred, threshold_pred)}
except:
record = {'Metric': "sm_precision_whole_batch", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "sm_precision_per_image", 'Score': sm_precision_per_image(y_test, pred, threshold_pred)}
except:
record = {'Metric': "sm_precision_per_image", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "np_precision_per_image", 'Score': np_p_r_f1(y_test, pred)[0]}
except:
record = {'Metric': "np_precision_per_image", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "sm_recall_whole_batch", 'Score': sm_recall_whole_batch(y_test, pred, threshold_pred)}
except:
record = {'Metric': "sm_recall_whole_batch", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "sm_recall_per_image", 'Score': sm_recall_per_image(y_test, pred, threshold_pred)}
except:
record = {'Metric': "sm_recall_per_image", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "np_recall_per_image", 'Score': np_p_r_f1(y_test, pred)[1]}
except:
record = {'Metric': "np_recall_per_image", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "np_sensitivity_per_image", 'Score': np_specificity_np_sensitivity(y_test, pred)[1]}
except:
record = {'Metric': "np_sensitivity_per_image", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "np_specificity_per_image", 'Score': np_specificity_np_sensitivity(y_test, pred)[0]}
except:
record = {'Metric': "np_specificity_per_image", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "np_object_precision_per_image", 'Score': np_object_p_r_f2(y_test, pred, threshold_pred)[0]}
except:
record = {'Metric': "np_object_precision_per_image", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "np_object_recall_per_image", 'Score': np_object_p_r_f2(y_test, pred, threshold_pred)[1]}
except:
record = {'Metric': "np_object_recall_per_image", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
try:
record = {'Metric': "np_object_f_per_image", 'Score': np_object_p_r_f2(y_test, pred, threshold_pred)[2]}
except:
record = {'Metric': "np_object_f_per_image", 'Score': -1}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
if all == 1:
dice_arr, jaccard_arr, precision_arr, recall_arr, fpr_arr, fnr_arr, vs_arr, hd_arr, hd95_arr, msd_arr, mdsd_arr, stdsd_arr, tp_arr, tn_arr, fp_arr, fn_arr, false_omission_rate_arr, accuracy_arr = seg_metrics_fuc(y_test, pred)
record = {'Metric': "dice_segmetric", 'Score': dice_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
record = {'Metric': "jaccard_segmetric", 'Score': jaccard_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
record = {'Metric': "precision_segmetric", 'Score': precision_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
record = {'Metric': "recall_segmetric", 'Score': recall_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
record = {'Metric': "fpr_segmetric", 'Score': fpr_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
record = {'Metric': "fnr_segmetric", 'Score': fnr_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
record = {'Metric': "vs_segmetric", 'Score': vs_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
record = {'Metric': "hd_segmetric", 'Score': hd_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
record = {'Metric': "hd95_segmetric", 'Score': hd95_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
record = {'Metric': "msd_segmetric", 'Score': msd_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
record = {'Metric': "mdsd_segmetric", 'Score': mdsd_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
record = {'Metric': "stdsd_segmetric", 'Score': stdsd_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
record = {'Metric': "tp_segmetric", 'Score': tp_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
record = {'Metric': "tn_segmetric", 'Score': tn_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
record = {'Metric': "fp_segmetric", 'Score': fp_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
record = {'Metric': "fn_segmetric", 'Score': fn_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
record = {'Metric': "false_omission_rate_segmetric", 'Score': false_omission_rate_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
record = {'Metric': "accuracy_segmetric", 'Score': accuracy_arr}
df = pd.concat([df,pd.DataFrame([record])], ignore_index=True)
return df
import colorsys
def generate_light_colors(n):
colors = []
for i in range(n):
hue = i / n
saturation = 0.3
value = 0.9
rgb = colorsys.hsv_to_rgb(hue, saturation, value)
hex_color = '#{:02x}{:02x}{:02x}'.format(int(rgb[0]*255), int(rgb[1]*255), int(rgb[2]*255))
colors.append(hex_color)
return colors
def generate_dark_colors(n):
colors = []
for i in range(n):
hue = i / n
saturation = 0.9
value = 0.3
rgb = colorsys.hsv_to_rgb(hue, saturation, value)
hex_color = '#{:02x}{:02x}{:02x}'.format(int(rgb[0]*255), int(rgb[1]*255), int(rgb[2]*255))
colors.append(hex_color)
return colors
def highlight_values_with_colors(dataframe, column):
unique_values = dataframe[column].unique()
value_counts = dataframe[column].value_counts()
dark_colors = generate_dark_colors(len(unique_values))
light_colors = generate_light_colors(len(unique_values))
color_map = {}
for i, val in enumerate(unique_values):
if value_counts[val] == 1: # Unique value
color_map[val] = (dark_colors[i % len(dark_colors)], 'white') # Dark color with white text
else: # Repeated value
color_map[val] = (light_colors[i % len(light_colors)], 'black') # Light color with black text
def apply_color(val):
if val in color_map:
bg_color, text_color = color_map[val]
return f'background-color: {bg_color}; color: {text_color};'
return ''
return dataframe.style.applymap(apply_color, subset=[column])
import csv
import datetime
def format_time(seconds):
"""Format time in seconds to hh:mm:ss:ms format."""
milliseconds = int((seconds - int(seconds)) * 1000)
formatted_time = str(datetime.timedelta(seconds=int(seconds))) + f":{milliseconds:03d}"
return formatted_time
def calc_time(epoch_times):
def format_time(seconds):
"""Format time in seconds to hh:mm:ss:ms format."""
milliseconds = int((seconds - int(seconds)) * 1000)
formatted_time = str(datetime.timedelta(seconds=int(seconds))) + f":{milliseconds:03d}"
return formatted_time
# Calculate the average epoch time excluding the first epoch
average_time_seconds = sum(epoch_times[1:]) / len(epoch_times[1:])
# Format the average time in hh:mm:ss:ms format
average_time_formatted = format_time(average_time_seconds)
# Calculate total training time
total_training_time_seconds = sum(epoch_times)
# Format the total training time in hh:mm:ss:ms format
total_training_time_formatted = format_time(total_training_time_seconds)
# List to store epoch data for CSV
epoch_data = []
# Process and print first 3 and last 3 epoch times in hh:mm:ss:ms format
num_epochs = len(epoch_times)
for i in range(num_epochs):
# Print only first 3 and last 3 epochs
if i < 3 or i >= num_epochs - 3:
formatted_time = format_time(epoch_times[i])
print(f"Epoch {i + 1} time: {formatted_time}")
epoch_data.append({"Epoch": i + 1, "Time (hh:mm:ss:ms)": formatted_time})
# Print the average epoch time excluding the first epoch
print(f"Average epoch time (excluding first epoch): {average_time_seconds:.3f} seconds")
print(f"Average epoch time (excluding first epoch): {average_time_formatted}")