Diff of /yolov5/utils/metrics.py [000000] .. [f26a44]

Switch to unified view

a b/yolov5/utils/metrics.py
1
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
"""
3
Model validation metrics
4
"""
5
6
import math
7
import warnings
8
from pathlib import Path
9
10
import matplotlib.pyplot as plt
11
import numpy as np
12
import torch
13
14
15
def fitness(x):
16
    # Model fitness as a weighted combination of metrics
17
    w = [0.0, 0.0, 0.1, 0.9]  # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
18
    return (x[:, :4] * w).sum(1)
19
20
21
def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=(), eps=1e-16):
22
    """ Compute the average precision, given the recall and precision curves.
23
    Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
24
    # Arguments
25
        tp:  True positives (nparray, nx1 or nx10).
26
        conf:  Objectness value from 0-1 (nparray).
27
        pred_cls:  Predicted object classes (nparray).
28
        target_cls:  True object classes (nparray).
29
        plot:  Plot precision-recall curve at mAP@0.5
30
        save_dir:  Plot save directory
31
    # Returns
32
        The average precision as computed in py-faster-rcnn.
33
    """
34
35
    # Sort by objectness
36
    i = np.argsort(-conf)
37
    tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
38
39
    # Find unique classes
40
    unique_classes, nt = np.unique(target_cls, return_counts=True)
41
    nc = unique_classes.shape[0]  # number of classes, number of detections
42
43
    # Create Precision-Recall curve and compute AP for each class
44
    px, py = np.linspace(0, 1, 1000), []  # for plotting
45
    ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
46
    for ci, c in enumerate(unique_classes):
47
        i = pred_cls == c
48
        n_l = nt[ci]  # number of labels
49
        n_p = i.sum()  # number of predictions
50
51
        if n_p == 0 or n_l == 0:
52
            continue
53
        else:
54
            # Accumulate FPs and TPs
55
            fpc = (1 - tp[i]).cumsum(0)
56
            tpc = tp[i].cumsum(0)
57
58
            # Recall
59
            recall = tpc / (n_l + eps)  # recall curve
60
            r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0)  # negative x, xp because xp decreases
61
62
            # Precision
63
            precision = tpc / (tpc + fpc)  # precision curve
64
            p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1)  # p at pr_score
65
66
            # AP from recall-precision curve
67
            for j in range(tp.shape[1]):
68
                ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
69
                if plot and j == 0:
70
                    py.append(np.interp(px, mrec, mpre))  # precision at mAP@0.5
71
72
    # Compute F1 (harmonic mean of precision and recall)
73
    f1 = 2 * p * r / (p + r + eps)
74
    names = [v for k, v in names.items() if k in unique_classes]  # list: only classes that have data
75
    names = {i: v for i, v in enumerate(names)}  # to dict
76
    if plot:
77
        plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)
78
        plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1')
79
        plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision')
80
        plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall')
81
82
    i = f1.mean(0).argmax()  # max F1 index
83
    p, r, f1 = p[:, i], r[:, i], f1[:, i]
84
    tp = (r * nt).round()  # true positives
85
    fp = (tp / (p + eps) - tp).round()  # false positives
86
    return tp, fp, p, r, f1, ap, unique_classes.astype('int32')
87
88
89
def compute_ap(recall, precision):
90
    """ Compute the average precision, given the recall and precision curves
91
    # Arguments
92
        recall:    The recall curve (list)
93
        precision: The precision curve (list)
94
    # Returns
95
        Average precision, precision curve, recall curve
96
    """
97
98
    # Append sentinel values to beginning and end
99
    mrec = np.concatenate(([0.0], recall, [1.0]))
100
    mpre = np.concatenate(([1.0], precision, [0.0]))
101
102
    # Compute the precision envelope
103
    mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
104
105
    # Integrate area under curve
106
    method = 'interp'  # methods: 'continuous', 'interp'
107
    if method == 'interp':
108
        x = np.linspace(0, 1, 101)  # 101-point interp (COCO)
109
        ap = np.trapz(np.interp(x, mrec, mpre), x)  # integrate
110
    else:  # 'continuous'
111
        i = np.where(mrec[1:] != mrec[:-1])[0]  # points where x axis (recall) changes
112
        ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])  # area under curve
113
114
    return ap, mpre, mrec
115
116
117
class ConfusionMatrix:
118
    # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
119
    def __init__(self, nc, conf=0.25, iou_thres=0.45):
120
        self.matrix = np.zeros((nc + 1, nc + 1))
121
        self.nc = nc  # number of classes
122
        self.conf = conf
123
        self.iou_thres = iou_thres
124
125
    def process_batch(self, detections, labels):
126
        """
127
        Return intersection-over-union (Jaccard index) of boxes.
128
        Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
129
        Arguments:
130
            detections (Array[N, 6]), x1, y1, x2, y2, conf, class
131
            labels (Array[M, 5]), class, x1, y1, x2, y2
132
        Returns:
133
            None, updates confusion matrix accordingly
134
        """
135
        detections = detections[detections[:, 4] > self.conf]
136
        gt_classes = labels[:, 0].int()
137
        detection_classes = detections[:, 5].int()
138
        iou = box_iou(labels[:, 1:], detections[:, :4])
139
140
        x = torch.where(iou > self.iou_thres)
141
        if x[0].shape[0]:
142
            matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
143
            if x[0].shape[0] > 1:
144
                matches = matches[matches[:, 2].argsort()[::-1]]
145
                matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
146
                matches = matches[matches[:, 2].argsort()[::-1]]
147
                matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
148
        else:
149
            matches = np.zeros((0, 3))
150
151
        n = matches.shape[0] > 0
152
        m0, m1, _ = matches.transpose().astype(np.int16)
153
        for i, gc in enumerate(gt_classes):
154
            j = m0 == i
155
            if n and sum(j) == 1:
156
                self.matrix[detection_classes[m1[j]], gc] += 1  # correct
157
            else:
158
                self.matrix[self.nc, gc] += 1  # background FP
159
160
        if n:
161
            for i, dc in enumerate(detection_classes):
162
                if not any(m1 == i):
163
                    self.matrix[dc, self.nc] += 1  # background FN
164
165
    def matrix(self):
166
        return self.matrix
167
168
    def tp_fp(self):
169
        tp = self.matrix.diagonal()  # true positives
170
        fp = self.matrix.sum(1) - tp  # false positives
171
        # fn = self.matrix.sum(0) - tp  # false negatives (missed detections)
172
        return tp[:-1], fp[:-1]  # remove background class
173
174
    def plot(self, normalize=True, save_dir='', names=()):
175
        try:
176
            import seaborn as sn
177
178
            array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-6) if normalize else 1)  # normalize columns
179
            array[array < 0.005] = np.nan  # don't annotate (would appear as 0.00)
180
181
            fig = plt.figure(figsize=(12, 9), tight_layout=True)
182
            sn.set(font_scale=1.0 if self.nc < 50 else 0.8)  # for label size
183
            labels = (0 < len(names) < 99) and len(names) == self.nc  # apply names to ticklabels
184
            with warnings.catch_warnings():
185
                warnings.simplefilter('ignore')  # suppress empty matrix RuntimeWarning: All-NaN slice encountered
186
                sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True,
187
                           xticklabels=names + ['background FP'] if labels else "auto",
188
                           yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1))
189
            fig.axes[0].set_xlabel('True')
190
            fig.axes[0].set_ylabel('Predicted')
191
            fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)
192
            plt.close()
193
        except Exception as e:
194
            print(f'WARNING: ConfusionMatrix plot failure: {e}')
195
196
    def print(self):
197
        for i in range(self.nc + 1):
198
            print(' '.join(map(str, self.matrix[i])))
199
200
201
def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):
202
    # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4
203
    box2 = box2.T
204
205
    # Get the coordinates of bounding boxes
206
    if x1y1x2y2:  # x1, y1, x2, y2 = box1
207
        b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
208
        b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
209
    else:  # transform from xywh to xyxy
210
        b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
211
        b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
212
        b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2
213
        b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2
214
215
    # Intersection area
216
    inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
217
            (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
218
219
    # Union Area
220
    w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
221
    w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
222
    union = w1 * h1 + w2 * h2 - inter + eps
223
224
    iou = inter / union
225
    if GIoU or DIoU or CIoU:
226
        cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1)  # convex (smallest enclosing box) width
227
        ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1)  # convex height
228
        if CIoU or DIoU:  # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
229
            c2 = cw ** 2 + ch ** 2 + eps  # convex diagonal squared
230
            rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 +
231
                    (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4  # center distance squared
232
            if DIoU:
233
                return iou - rho2 / c2  # DIoU
234
            elif CIoU:  # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
235
                v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
236
                with torch.no_grad():
237
                    alpha = v / (v - iou + (1 + eps))
238
                return iou - (rho2 / c2 + v * alpha)  # CIoU
239
        else:  # GIoU https://arxiv.org/pdf/1902.09630.pdf
240
            c_area = cw * ch + eps  # convex area
241
            return iou - (c_area - union) / c_area  # GIoU
242
    else:
243
        return iou  # IoU
244
245
246
def box_iou(box1, box2):
247
    # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
248
    """
249
    Return intersection-over-union (Jaccard index) of boxes.
250
    Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
251
    Arguments:
252
        box1 (Tensor[N, 4])
253
        box2 (Tensor[M, 4])
254
    Returns:
255
        iou (Tensor[N, M]): the NxM matrix containing the pairwise
256
            IoU values for every element in boxes1 and boxes2
257
    """
258
259
    def box_area(box):
260
        # box = 4xn
261
        return (box[2] - box[0]) * (box[3] - box[1])
262
263
    area1 = box_area(box1.T)
264
    area2 = box_area(box2.T)
265
266
    # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
267
    inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
268
    return inter / (area1[:, None] + area2 - inter)  # iou = inter / (area1 + area2 - inter)
269
270
271
def bbox_ioa(box1, box2, eps=1E-7):
272
    """ Returns the intersection over box2 area given box1, box2. Boxes are x1y1x2y2
273
    box1:       np.array of shape(4)
274
    box2:       np.array of shape(nx4)
275
    returns:    np.array of shape(n)
276
    """
277
278
    box2 = box2.transpose()
279
280
    # Get the coordinates of bounding boxes
281
    b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
282
    b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
283
284
    # Intersection area
285
    inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \
286
                 (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)
287
288
    # box2 area
289
    box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps
290
291
    # Intersection over box2 area
292
    return inter_area / box2_area
293
294
295
def wh_iou(wh1, wh2):
296
    # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2
297
    wh1 = wh1[:, None]  # [N,1,2]
298
    wh2 = wh2[None]  # [1,M,2]
299
    inter = torch.min(wh1, wh2).prod(2)  # [N,M]
300
    return inter / (wh1.prod(2) + wh2.prod(2) - inter)  # iou = inter / (area1 + area2 - inter)
301
302
303
# Plots ----------------------------------------------------------------------------------------------------------------
304
305
def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()):
306
    # Precision-recall curve
307
    fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
308
    py = np.stack(py, axis=1)
309
310
    if 0 < len(names) < 21:  # display per-class legend if < 21 classes
311
        for i, y in enumerate(py.T):
312
            ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}')  # plot(recall, precision)
313
    else:
314
        ax.plot(px, py, linewidth=1, color='grey')  # plot(recall, precision)
315
316
    ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())
317
    ax.set_xlabel('Recall')
318
    ax.set_ylabel('Precision')
319
    ax.set_xlim(0, 1)
320
    ax.set_ylim(0, 1)
321
    plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
322
    fig.savefig(Path(save_dir), dpi=250)
323
    plt.close()
324
325
326
def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'):
327
    # Metric-confidence curve
328
    fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
329
330
    if 0 < len(names) < 21:  # display per-class legend if < 21 classes
331
        for i, y in enumerate(py):
332
            ax.plot(px, y, linewidth=1, label=f'{names[i]}')  # plot(confidence, metric)
333
    else:
334
        ax.plot(px, py.T, linewidth=1, color='grey')  # plot(confidence, metric)
335
336
    y = py.mean(0)
337
    ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
338
    ax.set_xlabel(xlabel)
339
    ax.set_ylabel(ylabel)
340
    ax.set_xlim(0, 1)
341
    ax.set_ylim(0, 1)
342
    plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
343
    fig.savefig(Path(save_dir), dpi=250)
344
    plt.close()