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