-
Notifications
You must be signed in to change notification settings - Fork 7
/
metrics.py
107 lines (79 loc) · 2.42 KB
/
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
"""refence: https://github.com/neptune-ml/open-solution-data-science-bowl-2018/blob/master/src/metrics.py
"""
import numpy as np
from scipy.ndimage.measurements import label
def get_ious(pred, gt, threshold):
"""Caculate intersection over union between predcition and ground truth
Parameters
----------
pred:
predictions from the model
gt:
ground truth labels
threshold:
threshold used to seperate binary labels
"""
gt[gt > threshold] = 1.
gt[gt <= threshold] = 0.
pred[pred > threshold] = 1.
pred[pred <= threshold] = 0.
intersection = gt * pred
union = gt + pred
union[union > 0] = 1.
intersection = np.sum(intersection)
union = np.sum(union)
if union == 0:
union = 1e-09
return intersection / union
def compute_precision(pred, gt, threshold=0.5):
"""Compute the precision of IoU
Parameters
----------
pred:
predictions from the model
gt:
ground truth labels
threshold:
threshold used to seperate binary labels
"""
pred[pred > threshold] = 1.
pred[pred <= threshold] = 0.
structure = np.ones((3,3))
labeled, ncomponents = label(pred, structure)
pred_masks = []
for l in range(1,ncomponents):
pred_mask = np.zeros(labeled.shape)
pred_mask[labeled == l] = 1
pred_masks.append(pred_mask)
iou_vol = np.zeros([10, len(pred_masks), len(gt)])
for i, p in enumerate(pred_masks):
for j, g in enumerate(gt):
s = get_iou_vector(p, g)
iou_vol[:,i,j] = s
p = []
for iou_mat in iou_vol:
tp = np.sum(iou_mat.sum(axis=1) > 0)
fp = np.sum(iou_mat.sum(axis=1) == 0)
fn = np.sum(iou_mat.sum(axis=0) == 0)
p.append(tp / (tp + fp + fn))
return np.mean(p)
def get_iou_vector(pred, gt):
"""Compute the IoU hits with a range of thresholds
Parameters
----------
pred:
predictions from the model
gt:
ground truth labels
"""
intersection = np.logical_and(pred, gt)
union = np.logical_or(pred, gt)
intersection = np.sum(intersection)
union = np.sum(union)
if union == 0:
union = 1e-09
iou = np.sum(intersection > 0) / np.sum(union > 0)
s = []
for thresh in np.arange(0.5,1,0.05):
s.append(1 if iou > thresh else 0)
return s