hank1996 commited on
Commit
986ba9d
1 Parent(s): ebbd1df

Create new file

Browse files
Files changed (1) hide show
  1. utils/metrics.py +223 -0
utils/metrics.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from pathlib import Path
3
+
4
+ import matplotlib.pyplot as plt
5
+ import numpy as np
6
+ import torch
7
+
8
+ from . import general
9
+
10
+
11
+ def fitness(x):
12
+ # Model fitness as a weighted combination of metrics
13
+ w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
14
+ return (x[:, :4] * w).sum(1)
15
+
16
+
17
+ def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=()):
18
+ """ Compute the average precision, given the recall and precision curves.
19
+ Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
20
+ # Arguments
21
+ tp: True positives (nparray, nx1 or nx10).
22
+ conf: Objectness value from 0-1 (nparray).
23
+ pred_cls: Predicted object classes (nparray).
24
+ target_cls: True object classes (nparray).
25
+ plot: Plot precision-recall curve at mAP@0.5
26
+ save_dir: Plot save directory
27
+ # Returns
28
+ The average precision as computed in py-faster-rcnn.
29
+ """
30
+
31
+ # Sort by objectness
32
+ i = np.argsort(-conf)
33
+ tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
34
+
35
+ # Find unique classes
36
+ unique_classes = np.unique(target_cls)
37
+ nc = unique_classes.shape[0] # number of classes, number of detections
38
+
39
+ # Create Precision-Recall curve and compute AP for each class
40
+ px, py = np.linspace(0, 1, 1000), [] # for plotting
41
+ ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
42
+ for ci, c in enumerate(unique_classes):
43
+ i = pred_cls == c
44
+ n_l = (target_cls == c).sum() # number of labels
45
+ n_p = i.sum() # number of predictions
46
+
47
+ if n_p == 0 or n_l == 0:
48
+ continue
49
+ else:
50
+ # Accumulate FPs and TPs
51
+ fpc = (1 - tp[i]).cumsum(0)
52
+ tpc = tp[i].cumsum(0)
53
+
54
+ # Recall
55
+ recall = tpc / (n_l + 1e-16) # recall curve
56
+ r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
57
+
58
+ # Precision
59
+ precision = tpc / (tpc + fpc) # precision curve
60
+ p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score
61
+
62
+ # AP from recall-precision curve
63
+ for j in range(tp.shape[1]):
64
+ ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
65
+ if plot and j == 0:
66
+ py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5
67
+
68
+ # Compute F1 (harmonic mean of precision and recall)
69
+ f1 = 2 * p * r / (p + r + 1e-16)
70
+ if plot:
71
+ plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)
72
+ plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1')
73
+ plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision')
74
+ plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall')
75
+
76
+ i = f1.mean(0).argmax() # max F1 index
77
+ return p[:, i], r[:, i], ap, f1[:, i], unique_classes.astype('int32')
78
+
79
+
80
+ def compute_ap(recall, precision):
81
+ """ Compute the average precision, given the recall and precision curves
82
+ # Arguments
83
+ recall: The recall curve (list)
84
+ precision: The precision curve (list)
85
+ # Returns
86
+ Average precision, precision curve, recall curve
87
+ """
88
+
89
+ # Append sentinel values to beginning and end
90
+ mrec = np.concatenate(([0.], recall, [recall[-1] + 0.01]))
91
+ mpre = np.concatenate(([1.], precision, [0.]))
92
+
93
+ # Compute the precision envelope
94
+ mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
95
+
96
+ # Integrate area under curve
97
+ method = 'interp' # methods: 'continuous', 'interp'
98
+ if method == 'interp':
99
+ x = np.linspace(0, 1, 101) # 101-point interp (COCO)
100
+ ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
101
+ else: # 'continuous'
102
+ i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
103
+ ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
104
+
105
+ return ap, mpre, mrec
106
+
107
+
108
+ class ConfusionMatrix:
109
+ # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
110
+ def __init__(self, nc, conf=0.25, iou_thres=0.45):
111
+ self.matrix = np.zeros((nc + 1, nc + 1))
112
+ self.nc = nc # number of classes
113
+ self.conf = conf
114
+ self.iou_thres = iou_thres
115
+
116
+ def process_batch(self, detections, labels):
117
+ """
118
+ Return intersection-over-union (Jaccard index) of boxes.
119
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
120
+ Arguments:
121
+ detections (Array[N, 6]), x1, y1, x2, y2, conf, class
122
+ labels (Array[M, 5]), class, x1, y1, x2, y2
123
+ Returns:
124
+ None, updates confusion matrix accordingly
125
+ """
126
+ detections = detections[detections[:, 4] > self.conf]
127
+ gt_classes = labels[:, 0].int()
128
+ detection_classes = detections[:, 5].int()
129
+ iou = general.box_iou(labels[:, 1:], detections[:, :4])
130
+
131
+ x = torch.where(iou > self.iou_thres)
132
+ if x[0].shape[0]:
133
+ matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
134
+ if x[0].shape[0] > 1:
135
+ matches = matches[matches[:, 2].argsort()[::-1]]
136
+ matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
137
+ matches = matches[matches[:, 2].argsort()[::-1]]
138
+ matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
139
+ else:
140
+ matches = np.zeros((0, 3))
141
+
142
+ n = matches.shape[0] > 0
143
+ m0, m1, _ = matches.transpose().astype(np.int16)
144
+ for i, gc in enumerate(gt_classes):
145
+ j = m0 == i
146
+ if n and sum(j) == 1:
147
+ self.matrix[gc, detection_classes[m1[j]]] += 1 # correct
148
+ else:
149
+ self.matrix[self.nc, gc] += 1 # background FP
150
+
151
+ if n:
152
+ for i, dc in enumerate(detection_classes):
153
+ if not any(m1 == i):
154
+ self.matrix[dc, self.nc] += 1 # background FN
155
+
156
+ def matrix(self):
157
+ return self.matrix
158
+
159
+ def plot(self, save_dir='', names=()):
160
+ try:
161
+ import seaborn as sn
162
+
163
+ array = self.matrix / (self.matrix.sum(0).reshape(1, self.nc + 1) + 1E-6) # normalize
164
+ array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
165
+
166
+ fig = plt.figure(figsize=(12, 9), tight_layout=True)
167
+ sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size
168
+ labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels
169
+ sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True,
170
+ xticklabels=names + ['background FP'] if labels else "auto",
171
+ yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1))
172
+ fig.axes[0].set_xlabel('True')
173
+ fig.axes[0].set_ylabel('Predicted')
174
+ fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)
175
+ except Exception as e:
176
+ pass
177
+
178
+ def print(self):
179
+ for i in range(self.nc + 1):
180
+ print(' '.join(map(str, self.matrix[i])))
181
+
182
+
183
+ # Plots ----------------------------------------------------------------------------------------------------------------
184
+
185
+ def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()):
186
+ # Precision-recall curve
187
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
188
+ py = np.stack(py, axis=1)
189
+
190
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
191
+ for i, y in enumerate(py.T):
192
+ ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)
193
+ else:
194
+ ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
195
+
196
+ ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())
197
+ ax.set_xlabel('Recall')
198
+ ax.set_ylabel('Precision')
199
+ ax.set_xlim(0, 1)
200
+ ax.set_ylim(0, 1)
201
+ plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
202
+ fig.savefig(Path(save_dir), dpi=250)
203
+
204
+
205
+ def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'):
206
+ # Metric-confidence curve
207
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
208
+
209
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
210
+ for i, y in enumerate(py):
211
+ ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)
212
+ else:
213
+ ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)
214
+
215
+ y = py.mean(0)
216
+ ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
217
+ ax.set_xlabel(xlabel)
218
+ ax.set_ylabel(ylabel)
219
+ ax.set_xlim(0, 1)
220
+ ax.set_ylim(0, 1)
221
+ plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
222
+ fig.savefig(Path(save_dir), dpi=250)
223
+