-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmetrics_n.py
More file actions
67 lines (61 loc) · 2.44 KB
/
Copy pathmetrics_n.py
File metadata and controls
67 lines (61 loc) · 2.44 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
import torch
import numpy as np
from scipy.optimize import linear_sum_assignment
def IoUIoU(target, predicted_mask):
"""
Args:
target: (torch.tensor (batchxCxHxW)) Binary Target Segmentation from training set
predicted_mask: (torch.tensor (batchxCxHxW)) Predicted Segmentation Mask
Returns:
IoU: (Float) Average IoUs over Batch
"""
target = target.detach()
predicted_mask = predicted_mask.detach()
smooth = 1e-8
true_p = (torch.logical_and(target == 1, predicted_mask == 1)).sum()
# true_n = (torch.logical_and(target == 0, predicted_mask == 0)).sum().item() #Currently not needed for IoU
false_p = (torch.logical_and(target == 0, predicted_mask == 1)).sum()
false_n = (torch.logical_and(target == 1, predicted_mask == 0)).sum()
sample_IoU = (smooth+float(true_p))/(float(true_p) +
float(false_p)+float(false_n)+smooth)
return sample_IoU
def HM_IoU(Pred, Masks):
lcm = np.lcm(len(Pred), len(Masks))
len1 = len(Pred)
len2 = len(Masks)
for i in range((lcm // len1) - 1):
for j in range(len1):
Pred.append(Pred[j])
for i in range((lcm // len2) - 1):
for j in range(len2):
Masks.append(Masks[j])
cost_matrix = np.zeros((lcm, lcm))
for i in range(lcm):
for j in range(lcm):
cost_matrix[i][j] = 1 - IoUIoU(Pred[i], Masks[j])
row_ind, col_ind = linear_sum_assignment(cost_matrix)
HM_IoU = np.mean([(1 - cost_matrix[i][j]) for i, j in zip(row_ind, col_ind)])
return HM_IoU
def Dice(target, pred):
smooth = 1e-8
# all tensors remain on GPU, no dtype change
tp = (target * pred).sum(dim=[1,2,3]) # (N,)
denom = target.sum(dim=[1,2,3]) + pred.sum(dim=[1,2,3])
return (2 * tp + smooth) / (denom + smooth)
def IoU(target, pred):
smooth = 1e-8
tp = (target * pred).sum(dim=[1,2,3])
fp = ((1 - target) * pred).sum(dim=[1,2,3])
fn = (target * (1 - pred)).sum(dim=[1,2,3])
return (tp + smooth) / (tp + fp + fn + smooth)
def Dice_batch(pred, target):
smooth = 1e-8
tp = (pred * target).sum(dim=[1,2,3])
denom = pred.sum(dim=[1,2,3]) + target.sum(dim=[1,2,3])
return (2 * tp + smooth) / (denom + smooth)
def IoU_batch(pred, target):
smooth = 1e-8
tp = (pred * target).sum(dim=[1,2,3])
fp = ((1 - target) * pred).sum(dim=[1,2,3])
fn = (target * (1 - pred)).sum(dim=[1,2,3])
return (tp + smooth) / (tp + fp + fn + smooth)