Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/utils/metrics.py
Views: 475
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license1"""2Model validation metrics3"""45import math6import warnings7from pathlib import Path89import matplotlib.pyplot as plt10import numpy as np11import torch121314def fitness(x):15# Model fitness as a weighted combination of metrics16w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, [email protected], [email protected]:0.95]17return (x[:, :4] * w).sum(1)181920def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=(), eps=1e-16):21""" Compute the average precision, given the recall and precision curves.22Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.23# Arguments24tp: True positives (nparray, nx1 or nx10).25conf: Objectness value from 0-1 (nparray).26pred_cls: Predicted object classes (nparray).27target_cls: True object classes (nparray).28plot: Plot precision-recall curve at [email protected]29save_dir: Plot save directory30# Returns31The average precision as computed in py-faster-rcnn.32"""3334# Sort by objectness35i = np.argsort(-conf)36tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]3738# Find unique classes39unique_classes, nt = np.unique(target_cls, return_counts=True)40nc = unique_classes.shape[0] # number of classes, number of detections4142# Create Precision-Recall curve and compute AP for each class43px, py = np.linspace(0, 1, 1000), [] # for plotting44ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))45for ci, c in enumerate(unique_classes):46i = pred_cls == c47n_l = nt[ci] # number of labels48n_p = i.sum() # number of predictions4950if n_p == 0 or n_l == 0:51continue52else:53# Accumulate FPs and TPs54fpc = (1 - tp[i]).cumsum(0)55tpc = tp[i].cumsum(0)5657# Recall58recall = tpc / (n_l + eps) # recall curve59r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases6061# Precision62precision = tpc / (tpc + fpc) # precision curve63p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score6465# AP from recall-precision curve66for j in range(tp.shape[1]):67ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])68if plot and j == 0:69py.append(np.interp(px, mrec, mpre)) # precision at [email protected]7071# Compute F1 (harmonic mean of precision and recall)72f1 = 2 * p * r / (p + r + eps)73names = [v for k, v in names.items() if k in unique_classes] # list: only classes that have data74names = {i: v for i, v in enumerate(names)} # to dict75if plot:76plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)77plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1')78plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision')79plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall')8081i = f1.mean(0).argmax() # max F1 index82p, r, f1 = p[:, i], r[:, i], f1[:, i]83tp = (r * nt).round() # true positives84fp = (tp / (p + eps) - tp).round() # false positives85return tp, fp, p, r, f1, ap, unique_classes.astype('int32')868788def compute_ap(recall, precision):89""" Compute the average precision, given the recall and precision curves90# Arguments91recall: The recall curve (list)92precision: The precision curve (list)93# Returns94Average precision, precision curve, recall curve95"""9697# Append sentinel values to beginning and end98mrec = np.concatenate(([0.0], recall, [1.0]))99mpre = np.concatenate(([1.0], precision, [0.0]))100101# Compute the precision envelope102mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))103104# Integrate area under curve105method = 'interp' # methods: 'continuous', 'interp'106if method == 'interp':107x = np.linspace(0, 1, 101) # 101-point interp (COCO)108ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate109else: # 'continuous'110i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes111ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve112113return ap, mpre, mrec114115116class ConfusionMatrix:117# Updated version of https://github.com/kaanakan/object_detection_confusion_matrix118def __init__(self, nc, conf=0.25, iou_thres=0.45):119self.matrix = np.zeros((nc + 1, nc + 1))120self.nc = nc # number of classes121self.conf = conf122self.iou_thres = iou_thres123124def process_batch(self, detections, labels):125"""126Return intersection-over-union (Jaccard index) of boxes.127Both sets of boxes are expected to be in (x1, y1, x2, y2) format.128Arguments:129detections (Array[N, 6]), x1, y1, x2, y2, conf, class130labels (Array[M, 5]), class, x1, y1, x2, y2131Returns:132None, updates confusion matrix accordingly133"""134detections = detections[detections[:, 4] > self.conf]135gt_classes = labels[:, 0].int()136detection_classes = detections[:, 5].int()137iou = box_iou(labels[:, 1:], detections[:, :4])138139x = torch.where(iou > self.iou_thres)140if x[0].shape[0]:141matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()142if x[0].shape[0] > 1:143matches = matches[matches[:, 2].argsort()[::-1]]144matches = matches[np.unique(matches[:, 1], return_index=True)[1]]145matches = matches[matches[:, 2].argsort()[::-1]]146matches = matches[np.unique(matches[:, 0], return_index=True)[1]]147else:148matches = np.zeros((0, 3))149150n = matches.shape[0] > 0151m0, m1, _ = matches.transpose().astype(np.int16)152for i, gc in enumerate(gt_classes):153j = m0 == i154if n and sum(j) == 1:155self.matrix[detection_classes[m1[j]], gc] += 1 # correct156else:157self.matrix[self.nc, gc] += 1 # background FP158159if n:160for i, dc in enumerate(detection_classes):161if not any(m1 == i):162self.matrix[dc, self.nc] += 1 # background FN163164def matrix(self):165return self.matrix166167def tp_fp(self):168tp = self.matrix.diagonal() # true positives169fp = self.matrix.sum(1) - tp # false positives170# fn = self.matrix.sum(0) - tp # false negatives (missed detections)171return tp[:-1], fp[:-1] # remove background class172173def plot(self, normalize=True, save_dir='', names=()):174try:175import seaborn as sn176177array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-6) if normalize else 1) # normalize columns178array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)179180fig = plt.figure(figsize=(12, 9), tight_layout=True)181sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size182labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels183with warnings.catch_warnings():184warnings.simplefilter('ignore') # suppress empty matrix RuntimeWarning: All-NaN slice encountered185sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True,186xticklabels=names + ['background FP'] if labels else "auto",187yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1))188fig.axes[0].set_xlabel('True')189fig.axes[0].set_ylabel('Predicted')190fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)191plt.close()192except Exception as e:193print(f'WARNING: ConfusionMatrix plot failure: {e}')194195def print(self):196for i in range(self.nc + 1):197print(' '.join(map(str, self.matrix[i])))198199200def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):201# Returns the IoU of box1 to box2. box1 is 4, box2 is nx4202box2 = box2.T203204# Get the coordinates of bounding boxes205if x1y1x2y2: # x1, y1, x2, y2 = box1206b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]207b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]208else: # transform from xywh to xyxy209b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2210b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2211b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2212b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2213214# Intersection area215inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \216(torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)217218# Union Area219w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps220w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps221union = w1 * h1 + w2 * h2 - inter + eps222223iou = inter / union224if CIoU or DIoU or GIoU:225cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width226ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height227if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1228c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared229rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 +230(b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared231if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47232v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)233with torch.no_grad():234alpha = v / (v - iou + (1 + eps))235return iou - (rho2 / c2 + v * alpha) # CIoU236else:237return iou - rho2 / c2 # DIoU238else: # GIoU https://arxiv.org/pdf/1902.09630.pdf239c_area = cw * ch + eps # convex area240return iou - (c_area - union) / c_area # GIoU241else:242return iou # IoU243244245def box_iou(box1, box2):246# https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py247"""248Return intersection-over-union (Jaccard index) of boxes.249Both sets of boxes are expected to be in (x1, y1, x2, y2) format.250Arguments:251box1 (Tensor[N, 4])252box2 (Tensor[M, 4])253Returns:254iou (Tensor[N, M]): the NxM matrix containing the pairwise255IoU values for every element in boxes1 and boxes2256"""257258def box_area(box):259# box = 4xn260return (box[2] - box[0]) * (box[3] - box[1])261262area1 = box_area(box1.T)263area2 = box_area(box2.T)264265# inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)266inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)267return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)268269270def bbox_ioa(box1, box2, eps=1E-7):271""" Returns the intersection over box2 area given box1, box2. Boxes are x1y1x2y2272box1: np.array of shape(4)273box2: np.array of shape(nx4)274returns: np.array of shape(n)275"""276277box2 = box2.transpose()278279# Get the coordinates of bounding boxes280b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]281b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]282283# Intersection area284inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \285(np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)286287# box2 area288box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps289290# Intersection over box2 area291return inter_area / box2_area292293294def wh_iou(wh1, wh2):295# Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2296wh1 = wh1[:, None] # [N,1,2]297wh2 = wh2[None] # [1,M,2]298inter = torch.min(wh1, wh2).prod(2) # [N,M]299return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter)300301302# Plots ----------------------------------------------------------------------------------------------------------------303304def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()):305# Precision-recall curve306fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)307py = np.stack(py, axis=1)308309if 0 < len(names) < 21: # display per-class legend if < 21 classes310for i, y in enumerate(py.T):311ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)312else:313ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)314315ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f hbb [email protected]' % ap[:, 0].mean())316ax.set_xlabel('Recall')317ax.set_ylabel('Precision')318ax.set_xlim(0, 1)319ax.set_ylim(0, 1)320plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")321fig.savefig(Path(save_dir), dpi=250)322plt.close()323324325def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'):326# Metric-confidence curve327fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)328329if 0 < len(names) < 21: # display per-class legend if < 21 classes330for i, y in enumerate(py):331ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)332else:333ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)334335y = py.mean(0)336ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')337ax.set_xlabel(xlabel)338ax.set_ylabel(ylabel)339ax.set_xlim(0, 1)340ax.set_ylim(0, 1)341plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")342fig.savefig(Path(save_dir), dpi=250)343plt.close()344345346