car-detection-bayes/utils/utils.py

992 lines
40 KiB
Python
Raw Normal View History

2019-02-27 13:19:57 +00:00
import glob
2019-12-03 02:22:21 +00:00
import math
2019-07-25 11:19:26 +00:00
import os
2018-08-26 08:51:39 +00:00
import random
2019-08-03 20:51:19 +00:00
import shutil
2019-07-25 11:19:26 +00:00
from pathlib import Path
2018-08-26 08:51:39 +00:00
import cv2
2019-04-06 14:13:11 +00:00
import matplotlib
2019-02-27 13:19:57 +00:00
import matplotlib.pyplot as plt
2018-08-26 08:51:39 +00:00
import numpy as np
import torch
import torch.nn as nn
2019-12-03 02:22:21 +00:00
import torchvision
2019-05-29 16:04:11 +00:00
from tqdm import tqdm
2018-08-26 08:51:39 +00:00
2019-07-08 10:43:15 +00:00
from . import torch_utils # , google_utils
2019-06-21 11:19:23 +00:00
matplotlib.rc('font', **{'size': 11})
2019-04-06 14:13:11 +00:00
2018-09-02 09:15:39 +00:00
# Set printoptions
2019-08-23 10:57:26 +00:00
torch.set_printoptions(linewidth=320, precision=5, profile='long')
2018-10-03 11:55:56 +00:00
np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5
2018-08-26 08:51:39 +00:00
2019-03-21 20:41:12 +00:00
# Prevent OpenCV from multithreading (to use PyTorch DataLoader)
cv2.setNumThreads(0)
2018-08-26 08:51:39 +00:00
def init_seeds(seed=0):
random.seed(seed)
np.random.seed(seed)
torch_utils.init_seeds(seed=seed)
2018-08-26 08:51:39 +00:00
def load_classes(path):
2019-05-14 10:59:12 +00:00
# Loads *.names file at 'path'
with open(path, 'r') as f:
names = f.read().split('\n')
2018-12-28 20:12:31 +00:00
return list(filter(None, names)) # filter removes empty strings (such as last line)
2018-08-26 08:51:39 +00:00
2019-04-27 15:51:59 +00:00
def labels_to_class_weights(labels, nc=80):
2019-04-27 15:44:26 +00:00
# Get class weights (inverse frequency) from training labels
2019-11-20 21:36:15 +00:00
if labels[0] is None: # no labels loaded
2019-11-20 21:40:24 +00:00
return torch.Tensor()
2019-11-20 21:36:15 +00:00
2019-04-27 15:44:26 +00:00
labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO
2019-04-27 19:38:20 +00:00
classes = labels[:, 0].astype(np.int) # labels = [class xywh]
weights = np.bincount(classes, minlength=nc) # occurences per class
2019-08-17 12:09:38 +00:00
# Prepend gridpoint count (for uCE trianing)
2019-11-20 20:05:40 +00:00
# gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image
2019-11-20 21:36:15 +00:00
# weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start
2019-08-17 12:09:38 +00:00
2019-04-27 19:38:20 +00:00
weights[weights == 0] = 1 # replace empty bins with 1
weights = 1 / weights # number of targets per class
weights /= weights.sum() # normalize
2019-08-17 12:08:10 +00:00
return torch.from_numpy(weights)
2019-04-27 15:44:26 +00:00
2019-05-10 12:15:09 +00:00
def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):
# Produces image weights based on class mAPs
n = len(labels)
class_counts = np.array([np.bincount(labels[i][:, 0].astype(np.int), minlength=nc) for i in range(n)])
image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1)
# index = random.choices(range(n), weights=image_weights, k=1) # weight image sample
return image_weights
2019-02-19 18:00:44 +00:00
def coco_class_weights(): # frequency of each class in coco train2014
2019-05-05 11:44:12 +00:00
n = [187437, 4955, 30920, 6033, 3838, 4332, 3160, 7051, 7677, 9167, 1316, 1372, 833, 6757, 7355, 3302, 3776, 4671,
2018-10-10 14:16:17 +00:00
6769, 5706, 3908, 903, 3686, 3596, 6200, 7920, 8779, 4505, 4272, 1862, 4698, 1962, 4403, 6659, 2402, 2689,
4012, 4175, 3411, 17048, 5637, 14553, 3923, 5539, 4289, 10084, 7018, 4314, 3099, 4638, 4939, 5543, 2038, 4004,
5053, 4578, 27292, 4113, 5931, 2905, 11174, 2873, 4036, 3415, 1517, 4122, 1980, 4464, 1190, 2302, 156, 3933,
2019-05-05 11:44:12 +00:00
1877, 17630, 4337, 4624, 1075, 3468, 135, 1380]
weights = 1 / torch.Tensor(n)
2018-08-26 08:51:39 +00:00
weights /= weights.sum()
2019-09-11 19:24:22 +00:00
# with open('data/coco.names', 'r') as f:
# for k, v in zip(f.read().splitlines(), n):
# print('%20s: %g' % (k, v))
2018-10-10 14:16:17 +00:00
return weights
2018-08-26 08:51:39 +00:00
2019-02-27 12:21:39 +00:00
def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)
2019-02-26 01:53:11 +00:00
# https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/
2019-02-27 12:21:39 +00:00
# a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
# b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
2019-12-13 22:03:17 +00:00
# x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
# x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
2019-02-27 12:21:39 +00:00
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]
2019-02-26 13:57:28 +00:00
return x
2019-02-26 01:53:11 +00:00
2019-02-10 20:01:49 +00:00
def xyxy2xywh(x):
# Transform box coordinates from [x1, y1, x2, y2] (where xy1=top-left, xy2=bottom-right) to [x, y, w, h]
y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)
y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center
y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center
y[:, 2] = x[:, 2] - x[:, 0] # width
y[:, 3] = x[:, 3] - x[:, 1] # height
2018-09-02 09:15:39 +00:00
return y
2019-02-10 20:01:49 +00:00
def xywh2xyxy(x):
# Transform box coordinates from [x, y, w, h] to [x1, y1, x2, y2] (where xy1=top-left, xy2=bottom-right)
y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)
y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
2018-09-02 09:15:39 +00:00
return y
2018-08-26 08:51:39 +00:00
2019-12-24 21:41:52 +00:00
# def xywh2xyxy(box):
# # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2]
# if isinstance(box, torch.Tensor):
# x, y, w, h = box.t()
# return torch.stack((x - w / 2, y - h / 2, x + w / 2, y + h / 2)).t()
# else: # numpy
# x, y, w, h = box.T
# return np.stack((x - w / 2, y - h / 2, x + w / 2, y + h / 2)).T
#
#
# def xyxy2xywh(box):
# # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h]
# if isinstance(box, torch.Tensor):
# x1, y1, x2, y2 = box.t()
# return torch.stack(((x1 + x2) / 2, (y1 + y2) / 2, x2 - x1, y2 - y1)).t()
# else: # numpy
# x1, y1, x2, y2 = box.T
# return np.stack(((x1 + x2) / 2, (y1 + y2) / 2, x2 - x1, y2 - y1)).T
2019-12-01 02:19:17 +00:00
def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):
2019-07-15 14:27:13 +00:00
# Rescale coords (xyxy) from img1_shape to img0_shape
2019-12-01 02:45:43 +00:00
if ratio_pad is None: # calculate from img0_shape
2019-12-01 02:19:17 +00:00
gain = max(img1_shape) / max(img0_shape) # gain = old / new
pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
else:
gain = ratio_pad[0][0]
pad = ratio_pad[1]
coords[:, [0, 2]] -= pad[0] # x padding
coords[:, [1, 3]] -= pad[1] # y padding
2019-02-10 20:01:49 +00:00
coords[:, :4] /= gain
2019-07-15 14:48:02 +00:00
clip_coords(coords, img0_shape)
2019-02-10 20:01:49 +00:00
return coords
2019-07-15 14:27:13 +00:00
def clip_coords(boxes, img_shape):
# Clip bounding xyxy bounding boxes to image shape (height, width)
boxes[:, 0].clamp_(0, img_shape[1]) # x1
boxes[:, 1].clamp_(0, img_shape[0]) # y1
boxes[:, 2].clamp_(0, img_shape[1]) # x2
boxes[:, 3].clamp_(0, img_shape[0]) # y2
2019-07-15 14:27:13 +00:00
2018-09-10 13:12:13 +00:00
def ap_per_class(tp, conf, pred_cls, target_cls):
""" Compute the average precision, given the recall and precision curves.
Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
2018-09-10 13:12:13 +00:00
# Arguments
2019-12-16 23:49:15 +00:00
tp: True positives (nparray, nx1 or nx10).
conf: Objectness value from 0-1 (nparray).
pred_cls: Predicted object classes (nparray).
target_cls: True object classes (nparray).
2018-09-10 13:12:13 +00:00
# Returns
The average precision as computed in py-faster-rcnn.
"""
# Sort by objectness
i = np.argsort(-conf)
tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
# Find unique classes
unique_classes = np.unique(target_cls)
2018-09-10 13:12:13 +00:00
# Create Precision-Recall curve and compute AP for each class
2020-03-12 04:30:47 +00:00
pr_score = 0.1 # score to evaluate P and R https://github.com/ultralytics/yolov3/issues/898
2019-12-16 23:49:15 +00:00
s = [len(unique_classes), tp.shape[1]] # number class, number iou thresholds (i.e. 10 for mAP0.5...0.95)
ap, p, r = np.zeros(s), np.zeros(s), np.zeros(s)
for ci, c in enumerate(unique_classes):
2018-09-10 13:12:13 +00:00
i = pred_cls == c
2019-12-21 17:32:47 +00:00
n_gt = (target_cls == c).sum() # Number of ground truth objects
n_p = i.sum() # Number of predicted objects
2018-09-10 13:12:13 +00:00
2019-12-16 23:49:15 +00:00
if n_p == 0 or n_gt == 0:
2018-09-10 14:31:56 +00:00
continue
2018-09-10 13:12:13 +00:00
else:
# Accumulate FPs and TPs
2019-12-16 23:49:15 +00:00
fpc = (1 - tp[i]).cumsum(0)
tpc = tp[i].cumsum(0)
2018-09-10 13:12:13 +00:00
# Recall
2019-08-06 12:57:12 +00:00
recall = tpc / (n_gt + 1e-16) # recall curve
2020-03-07 18:26:08 +00:00
r[ci] = np.interp(-pr_score, -conf[i], recall[:, 0]) # r at pr_score, negative x, xp because xp decreases
2018-09-10 13:12:13 +00:00
# Precision
2019-08-06 12:57:12 +00:00
precision = tpc / (tpc + fpc) # precision curve
2020-03-07 18:26:08 +00:00
p[ci] = np.interp(-pr_score, -conf[i], precision[:, 0]) # p at pr_score
2018-09-10 13:12:13 +00:00
# AP from recall-precision curve
2019-12-16 23:49:15 +00:00
for j in range(tp.shape[1]):
ap[ci, j] = compute_ap(recall[:, j], precision[:, j])
2018-09-10 13:12:13 +00:00
2019-04-02 11:43:18 +00:00
# Plot
2020-03-07 18:26:08 +00:00
# fig, ax = plt.subplots(1, 1, figsize=(5, 5))
2020-01-29 19:58:32 +00:00
# ax.plot(recall, precision)
# ax.set_xlabel('Recall')
# ax.set_ylabel('Precision')
# ax.set_xlim(0, 1.01)
# ax.set_ylim(0, 1.01)
2019-08-06 12:57:12 +00:00
# fig.tight_layout()
# fig.savefig('PR_curve.png', dpi=300)
2019-04-02 11:43:18 +00:00
2019-04-05 13:34:42 +00:00
# Compute F1 score (harmonic mean of precision and recall)
f1 = 2 * p * r / (p + r + 1e-16)
return p, r, ap, f1, unique_classes.astype('int32')
2018-09-10 13:12:13 +00:00
2018-08-26 08:51:39 +00:00
def compute_ap(recall, precision):
""" Compute the average precision, given the recall and precision curves.
Source: https://github.com/rbgirshick/py-faster-rcnn.
2018-08-26 08:51:39 +00:00
# Arguments
recall: The recall curve (list).
precision: The precision curve (list).
# Returns
The average precision as computed in py-faster-rcnn.
"""
2019-10-01 14:04:56 +00:00
2019-08-06 12:57:12 +00:00
# Append sentinel values to beginning and end
2019-10-01 15:24:33 +00:00
mrec = np.concatenate(([0.], recall, [min(recall[-1] + 1E-3, 1.)]))
2018-08-26 08:51:39 +00:00
mpre = np.concatenate(([0.], precision, [0.]))
2019-08-06 12:57:12 +00:00
# Compute the precision envelope
2019-12-24 20:26:35 +00:00
mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
2018-08-26 08:51:39 +00:00
2019-10-01 14:04:56 +00:00
# Integrate area under curve
method = 'interp' # methods: 'continuous', 'interp'
if method == 'interp':
x = np.linspace(0, 1, 101) # 101-point interp (COCO)
ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
else: # 'continuous'
i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
2018-08-26 08:51:39 +00:00
return ap
2019-11-24 05:23:31 +00:00
def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False):
# Returns the IoU of box1 to box2. box1 is 4, box2 is nx4
2019-03-15 18:40:37 +00:00
box2 = box2.t()
# Get the coordinates of bounding boxes
2019-11-25 18:26:26 +00:00
if x1y1x2y2: # x1, y1, x2, y2 = box1
2019-03-15 18:40:37 +00:00
b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
else: # transform from xywh to xyxy
2019-03-15 18:40:37 +00:00
b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2
b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2
2018-08-26 08:51:39 +00:00
# Intersection area
2019-12-22 22:19:46 +00:00
inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
(torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
2018-08-26 08:51:39 +00:00
# Union Area
2019-11-24 05:23:31 +00:00
w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1
w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1
2019-12-22 22:19:46 +00:00
union = (w1 * h1 + 1e-16) + w2 * h2 - inter
2018-08-26 08:51:39 +00:00
2019-12-22 22:19:46 +00:00
iou = inter / union # iou
2019-11-24 05:23:31 +00:00
if GIoU or DIoU or CIoU:
cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
if GIoU: # Generalized IoU https://arxiv.org/pdf/1902.09630.pdf
c_area = cw * ch + 1e-16 # convex area
2019-12-22 22:19:46 +00:00
return iou - (c_area - union) / c_area # GIoU
2019-11-25 06:08:24 +00:00
if DIoU or CIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
# convex diagonal squared
c2 = cw ** 2 + ch ** 2 + 1e-16
# centerpoint distance squared
2019-11-24 05:23:31 +00:00
rho2 = ((b2_x1 + b2_x2) - (b1_x1 + b1_x2)) ** 2 / 4 + ((b2_y1 + b2_y2) - (b1_y1 + b1_y2)) ** 2 / 4
if DIoU:
return iou - rho2 / c2 # DIoU
2019-11-30 02:20:57 +00:00
elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
2019-11-25 06:08:24 +00:00
v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
2019-11-30 02:20:57 +00:00
with torch.no_grad():
alpha = v / (1 - iou + v)
return iou - (rho2 / c2 + v * alpha) # CIoU
2019-06-12 12:30:40 +00:00
return iou
2018-08-26 08:51:39 +00:00
2018-09-09 14:14:24 +00:00
2020-03-31 22:37:23 +00:00
def box_iou(box1, box2):
2019-12-22 21:26:46 +00:00
# https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
"""
Return intersection-over-union (Jaccard index) of boxes.
Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
Arguments:
2020-03-31 22:37:23 +00:00
box1 (Tensor[N, 4])
box2 (Tensor[M, 4])
2019-12-22 21:26:46 +00:00
Returns:
iou (Tensor[N, M]): the NxM matrix containing the pairwise
IoU values for every element in boxes1 and boxes2
"""
2019-12-22 22:19:46 +00:00
def box_area(box):
# box = 4xn
return (box[2] - box[0]) * (box[3] - box[1])
2019-12-22 21:26:46 +00:00
2020-03-31 22:37:23 +00:00
area1 = box_area(box1.t())
area2 = box_area(box2.t())
2019-12-22 21:26:46 +00:00
2020-03-31 22:37:23 +00:00
# inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
2019-12-22 22:19:46 +00:00
return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)
2019-12-22 21:26:46 +00:00
2019-12-22 22:05:40 +00:00
def wh_iou(wh1, wh2):
# Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2
wh1 = wh1[:, None] # [N,1,2]
wh2 = wh2[None] # [1,M,2]
inter = torch.min(wh1, wh2).prod(2) # [N,M]
return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter)
2019-08-17 23:58:35 +00:00
class FocalLoss(nn.Module):
2020-03-16 21:03:50 +00:00
# Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
2019-08-17 23:58:35 +00:00
super(FocalLoss, self).__init__()
2020-03-16 21:03:50 +00:00
self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
2019-08-17 23:58:35 +00:00
self.gamma = gamma
2019-09-10 09:35:46 +00:00
self.alpha = alpha
2020-01-31 17:00:45 +00:00
self.reduction = loss_fcn.reduction
self.loss_fcn.reduction = 'none' # required to apply FL to each element
2019-08-17 23:58:35 +00:00
2020-03-16 21:03:50 +00:00
def forward(self, pred, true):
loss = self.loss_fcn(pred, true)
2020-03-16 21:18:56 +00:00
# p_t = torch.exp(-loss)
# loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
2020-03-16 21:03:50 +00:00
# TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
pred_prob = torch.sigmoid(pred) # prob from logits
p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
modulating_factor = (1.0 - p_t) ** self.gamma
2020-03-17 04:40:57 +00:00
loss *= alpha_factor * modulating_factor
2019-08-17 23:58:35 +00:00
if self.reduction == 'mean':
return loss.mean()
elif self.reduction == 'sum':
return loss.sum()
else: # 'none'
return loss
2020-03-12 08:09:17 +00:00
def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
# return positive, negative label smoothing BCE targets
return 1.0 - 0.5 * eps, 0.5 * eps
2020-03-04 21:20:08 +00:00
def compute_loss(p, targets, model): # predictions, targets, model
2019-04-16 10:49:34 +00:00
ft = torch.cuda.FloatTensor if p[0].is_cuda else torch.Tensor
2019-08-17 17:20:39 +00:00
lcls, lbox, lobj = ft([0]), ft([0]), ft([0])
tcls, tbox, indices, anchor_vec = build_targets(p, targets, model)
2019-06-12 17:40:21 +00:00
h = model.hyp # hyperparameters
2020-02-17 07:12:07 +00:00
red = 'mean' # Loss reduction (sum or mean)
2019-04-17 13:52:51 +00:00
# Define criteria
2019-12-09 04:15:25 +00:00
BCEcls = nn.BCEWithLogitsLoss(pos_weight=ft([h['cls_pw']]), reduction=red)
BCEobj = nn.BCEWithLogitsLoss(pos_weight=ft([h['obj_pw']]), reduction=red)
2019-08-25 18:19:53 +00:00
2020-03-08 23:15:41 +00:00
# class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
2020-03-12 08:09:17 +00:00
cp, cn = smooth_BCE(eps=0.0)
2020-03-08 23:15:41 +00:00
2020-03-17 00:31:37 +00:00
# focal loss
g = h['fl_gamma'] # focal loss gamma
if g > 0:
BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
# Compute losses
2019-12-09 04:15:25 +00:00
np, ng = 0, 0 # number grid points, targets
2019-08-18 19:28:49 +00:00
for i, pi in enumerate(p): # layer index, layer predictions
2019-04-26 11:28:00 +00:00
b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
2019-08-18 19:24:48 +00:00
tobj = torch.zeros_like(pi[..., 0]) # target obj
2019-12-09 04:15:25 +00:00
np += tobj.numel()
# Compute losses
2019-07-12 10:24:43 +00:00
nb = len(b)
if nb: # number of targets
2019-12-09 04:15:25 +00:00
ng += nb
2019-08-18 19:24:48 +00:00
ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
# ps[:, 2:4] = torch.sigmoid(ps[:, 2:4]) # wh power loss (uncomment)
2019-08-17 17:20:39 +00:00
# GIoU
2019-08-18 19:24:48 +00:00
pxy = torch.sigmoid(ps[:, 0:2]) # pxy = pxy * s - (s - 1) / 2, s = 1.5 (scale_xy)
2019-12-23 20:24:48 +00:00
pwh = torch.exp(ps[:, 2:4]).clamp(max=1E3) * anchor_vec[i]
pbox = torch.cat((pxy, pwh), 1) # predicted box
2019-12-27 19:51:27 +00:00
giou = bbox_iou(pbox.t(), tbox[i], x1y1x2y2=False, GIoU=True) # giou computation
lbox += (1.0 - giou).sum() if red == 'sum' else (1.0 - giou).mean() # giou loss
2020-03-17 04:40:57 +00:00
tobj[b, a, gj, gi] = (1.0 - model.gr) + model.gr * giou.detach().clamp(0).type(tobj.dtype) # giou ratio
2019-08-17 17:20:39 +00:00
2020-03-17 00:31:37 +00:00
if model.nc > 1: # cls loss (only if multiple classes)
t = torch.full_like(ps[:, 5:], cn) # targets
2020-03-08 23:13:56 +00:00
t[range(nb), tcls[i]] = cp
2019-08-18 19:24:48 +00:00
lcls += BCEcls(ps[:, 5:], t) # BCE
# lcls += CE(ps[:, 5:], tcls[i]) # CE
2019-06-30 15:34:29 +00:00
# Append targets to text file
2019-06-22 17:21:05 +00:00
# with open('targets.txt', 'a') as file:
# [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
2020-03-17 00:31:37 +00:00
lobj += BCEobj(pi[..., 4], tobj) # obj loss
2019-08-17 17:20:39 +00:00
2019-08-24 21:58:08 +00:00
lbox *= h['giou']
lobj *= h['obj']
lcls *= h['cls']
2019-12-09 04:15:25 +00:00
if red == 'sum':
2019-12-30 23:41:47 +00:00
bs = tobj.shape[0] # batch size
lobj *= 3 / (6300 * bs) * 2 # 3 / np * 2
2020-01-06 20:35:10 +00:00
if ng:
lcls *= 3 / ng / model.nc
lbox *= 3 / ng
2019-12-09 04:15:25 +00:00
2019-08-17 17:20:39 +00:00
loss = lbox + lobj + lcls
2019-08-24 14:43:43 +00:00
return loss, torch.cat((lbox, lobj, lcls, loss)).detach()
def build_targets(p, targets, model):
# targets = [image, class, x, y, w, h]
2020-03-27 01:41:04 +00:00
nt = targets.shape[0]
2019-08-17 17:20:39 +00:00
tcls, tbox, indices, av = [], [], [], []
2019-12-09 01:19:42 +00:00
reject, use_all_anchors = True, True
gain = torch.ones(6, device=targets.device) # normalized to gridspace gain
2020-04-14 11:34:40 +00:00
# m = list(model.modules())[-1]
# for i in range(m.nl):
# anchor_vec = m.anchor_vec[i]
2020-04-14 11:15:05 +00:00
multi_gpu = type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
for i, j in enumerate(model.yolo_layers):
2019-08-05 15:41:25 +00:00
# get number of grid points and anchor vec for this yolo layer
2020-04-14 11:15:05 +00:00
anchor_vec = model.module.module_list[j].anchor_vec if multi_gpu else model.module_list[j].anchor_vec
# iou of targets-anchors
2020-04-14 11:34:40 +00:00
gain[2:] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
t, a = targets * gain, []
gwh = t[:, 4:6]
if nt:
2020-03-27 01:34:20 +00:00
iou = wh_iou(anchor_vec, gwh) # iou(3,n) = wh_iou(anchor_vec(3,2), gwh(n,2))
2019-07-04 20:50:03 +00:00
2019-12-09 01:19:42 +00:00
if use_all_anchors:
2020-03-27 01:34:20 +00:00
na = anchor_vec.shape[0] # number of anchors
a = torch.arange(na).view(-1, 1).repeat(1, nt).view(-1)
2020-04-14 10:13:30 +00:00
t = t.repeat(na, 1)
2019-12-09 01:19:42 +00:00
else: # use best anchor only
iou, a = iou.max(0) # best iou and anchor
2019-07-04 22:36:37 +00:00
# reject anchors below iou_thres (OPTIONAL, increases P, lowers R)
if reject:
2019-12-09 00:02:55 +00:00
j = iou.view(-1) > model.hyp['iou_t'] # iou threshold hyperparameter
t, a = t[j], a[j]
# Indices
2019-03-31 17:57:44 +00:00
b, c = t[:, :2].long().t() # target image, class
gxy = t[:, 2:4] # grid x, y
gwh = t[:, 4:6] # grid w, h
2019-04-26 11:28:00 +00:00
gi, gj = gxy.long().t() # grid x, y indices
indices.append((b, a, gj, gi))
2018-08-26 08:51:39 +00:00
2019-12-22 21:07:00 +00:00
# Box
2019-08-17 17:20:39 +00:00
gxy -= gxy.floor() # xy
2019-06-12 12:30:40 +00:00
tbox.append(torch.cat((gxy, gwh), 1)) # xywh (grids)
2019-08-05 15:41:25 +00:00
av.append(anchor_vec[a]) # anchor vec
2018-09-20 16:03:19 +00:00
# Class
tcls.append(c)
2019-08-05 14:59:32 +00:00
if c.shape[0]: # if any targets
2019-12-03 21:49:20 +00:00
assert c.max() < model.nc, 'Model accepts %g classes labeled from 0-%g, however you labelled a class %g. ' \
'See https://github.com/ultralytics/yolov3/wiki/Train-Custom-Data' % (
model.nc, model.nc - 1, c.max())
2018-08-26 08:51:39 +00:00
2019-08-17 17:20:39 +00:00
return tcls, tbox, indices, av
2018-08-26 08:51:39 +00:00
2020-03-05 22:20:52 +00:00
def non_max_suppression(prediction, conf_thres=0.1, iou_thres=0.6, multi_label=True, classes=None, agnostic=False):
2018-08-26 08:51:39 +00:00
"""
2020-03-26 19:33:12 +00:00
Performs Non-Maximum Suppression on inference results
2018-08-26 08:51:39 +00:00
Returns detections with shape:
2020-03-26 19:33:12 +00:00
nx6 (x1, y1, x2, y2, conf, cls)
2018-08-26 08:51:39 +00:00
"""
2019-12-17 18:14:18 +00:00
# Box constraints
2019-12-29 23:31:57 +00:00
min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height
2020-03-26 19:33:12 +00:00
method = 'merge'
2020-01-18 01:44:22 +00:00
nc = prediction[0].shape[1] - 5 # number of classes
2020-03-05 22:20:52 +00:00
multi_label &= nc > 1 # multiple labels per box
output = [None] * len(prediction)
2020-03-31 22:37:23 +00:00
2020-03-26 19:33:12 +00:00
for xi, x in enumerate(prediction): # image index, image inference
2019-12-23 19:05:55 +00:00
# Apply conf constraint
2020-03-26 19:33:12 +00:00
x = x[x[:, 4] > conf_thres]
2019-10-08 16:13:04 +00:00
2019-12-23 18:10:24 +00:00
# Apply width-height constraint
2020-03-26 19:33:12 +00:00
x = x[((x[:, 2:4] > min_wh) & (x[:, 2:4] < max_wh)).all(1)]
2018-08-26 08:51:39 +00:00
2020-03-05 17:54:41 +00:00
# If none remain process next image
2020-03-26 19:33:12 +00:00
if not x.shape[0]:
2020-03-05 17:54:41 +00:00
continue
2019-12-23 19:05:55 +00:00
# Compute conf
2020-03-26 19:33:12 +00:00
x[..., 5:] *= x[..., 4:5] # conf = obj_conf * cls_conf
2019-12-23 19:05:55 +00:00
# Box (center x, center y, width, height) to (x1, y1, x2, y2)
2020-03-26 19:33:12 +00:00
box = xywh2xyxy(x[:, :4])
2019-12-23 18:30:13 +00:00
# Detections matrix nx6 (xyxy, conf, cls)
2020-03-05 22:20:52 +00:00
if multi_label:
2020-03-26 19:33:12 +00:00
i, j = (x[:, 5:] > conf_thres).nonzero().t()
x = torch.cat((box[i], x[i, j + 5].unsqueeze(1), j.float().unsqueeze(1)), 1)
2019-12-20 03:23:09 +00:00
else: # best class only
2020-03-26 19:33:12 +00:00
conf, j = x[:, 5:].max(1)
x = torch.cat((box, conf.unsqueeze(1), j.float().unsqueeze(1)), 1)
2018-08-26 08:51:39 +00:00
2020-01-01 20:44:33 +00:00
# Filter by class
if classes:
2020-03-26 19:33:12 +00:00
x = x[(j.view(-1, 1) == torch.tensor(classes, device=j.device)).any(1)]
2020-01-01 20:44:33 +00:00
2019-12-23 18:22:07 +00:00
# Apply finite constraint
2020-03-26 19:33:12 +00:00
if not torch.isfinite(x).all():
x = x[torch.isfinite(x).all(1)]
2019-12-23 18:22:07 +00:00
2020-03-04 03:16:13 +00:00
# If none remain process next image
2020-03-30 03:41:32 +00:00
n = x.shape[0] # number of boxes
if not n:
2020-03-04 03:16:13 +00:00
continue
2019-12-25 22:47:50 +00:00
# Sort by confidence
2020-03-26 19:20:01 +00:00
# if method == 'fast_batch':
2020-03-26 19:33:12 +00:00
# x = x[x[:, 4].argsort(descending=True)]
2019-12-25 22:47:50 +00:00
2020-03-04 08:07:19 +00:00
# Batched NMS
2020-03-26 19:33:12 +00:00
c = x[:, 5] * 0 if agnostic else x[:, 5] # classes
boxes, scores = x[:, :4].clone() + c.view(-1, 1) * max_wh, x[:, 4] # boxes (offset by class), scores
if method == 'merge': # Merge NMS (boxes merged using weighted mean)
2020-03-26 19:20:01 +00:00
i = torchvision.ops.boxes.nms(boxes, scores, iou_thres)
2020-04-03 01:53:40 +00:00
if n < 1E4: # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
2020-04-01 04:31:09 +00:00
# weights = (box_iou(boxes, boxes).tril_() > iou_thres) * scores.view(-1, 1) # box weights
# weights /= weights.sum(0) # normalize
# x[:, :4] = torch.mm(weights.T, x[:, :4])
weights = (box_iou(boxes[i], boxes) > iou_thres) * scores[None] # box weights
2020-04-03 01:53:40 +00:00
x[i, :4] = torch.mm(weights / weights.sum(1, keepdim=True), x[:, :4]).float() # merged boxes
2020-03-26 19:33:12 +00:00
elif method == 'vision':
i = torchvision.ops.boxes.nms(boxes, scores, iou_thres)
2020-03-26 19:20:01 +00:00
elif method == 'fast': # FastNMS from https://github.com/dbolya/yolact
iou = box_iou(boxes, boxes).triu_(diagonal=1) # upper triangular iou matrix
i = iou.max(0)[0] < iou_thres
2020-03-26 19:33:12 +00:00
output[xi] = x[i]
2020-03-26 19:48:00 +00:00
return output
2018-08-26 08:51:39 +00:00
def get_yolo_layers(model):
bool_vec = [x['type'] == 'yolo' for x in model.module_defs]
return [i for i, x in enumerate(bool_vec) if x] # [82, 94, 106] for yolov3
2019-08-22 14:39:55 +00:00
def print_model_biases(model):
# prints the bias neurons preceding each yolo layer
2020-01-17 18:49:07 +00:00
print('\nModel Bias Summary: %8s%18s%18s%18s' % ('layer', 'regression', 'objectness', 'classification'))
2020-04-14 18:51:19 +00:00
try:
multi_gpu = type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
for l in model.yolo_layers: # print pretrained biases
2020-03-12 08:09:17 +00:00
if multi_gpu:
na = model.module.module_list[l].na # number of anchors
b = model.module.module_list[l - 1][0].bias.view(na, -1) # bias 3x85
else:
na = model.module_list[l].na
b = model.module_list[l - 1][0].bias.view(na, -1) # bias 3x85
print(' ' * 20 + '%8g %18s%18s%18s' % (l, '%5.2f+/-%-5.2f' % (b[:, :4].mean(), b[:, :4].std()),
'%5.2f+/-%-5.2f' % (b[:, 4].mean(), b[:, 4].std()),
'%5.2f+/-%-5.2f' % (b[:, 5:].mean(), b[:, 5:].std())))
except:
pass
2019-08-22 14:39:55 +00:00
2019-08-24 18:55:01 +00:00
def strip_optimizer(f='weights/last.pt'): # from utils.utils import *; strip_optimizer()
2018-08-26 08:51:39 +00:00
# Strip optimizer from *.pt files for lighter files (reduced by 2/3 size)
2019-11-15 01:32:28 +00:00
x = torch.load(f, map_location=torch.device('cpu'))
2019-08-24 10:37:55 +00:00
x['optimizer'] = None
torch.save(x, f)
2018-08-26 08:51:39 +00:00
2019-08-24 18:55:01 +00:00
def create_backbone(f='weights/last.pt'): # from utils.utils import *; create_backbone()
# create a backbone from a *.pt file
2019-11-15 03:14:00 +00:00
x = torch.load(f, map_location=torch.device('cpu'))
2019-08-24 18:55:01 +00:00
x['optimizer'] = None
x['training_results'] = None
x['epoch'] = -1
for p in x['model'].values():
try:
p.requires_grad = True
except:
pass
torch.save(x, 'weights/backbone.pt')
2018-12-03 20:08:45 +00:00
def coco_class_count(path='../coco/labels/train2014/'):
# Histogram of occurrences per class
2019-04-19 18:41:18 +00:00
nc = 80 # number classes
x = np.zeros(nc, dtype='int32')
2018-10-10 14:16:17 +00:00
files = sorted(glob.glob('%s/*.*' % path))
for i, file in enumerate(files):
labels = np.loadtxt(file, dtype=np.float32).reshape(-1, 5)
2019-04-19 18:41:18 +00:00
x += np.bincount(labels[:, 0].astype('int32'), minlength=nc)
2018-10-10 14:16:17 +00:00
print(i, len(files))
2019-12-14 02:52:08 +00:00
def coco_only_people(path='../coco/labels/train2017/'): # from utils.utils import *; coco_only_people()
# Find images with only people
2019-02-20 14:11:55 +00:00
files = sorted(glob.glob('%s/*.*' % path))
for i, file in enumerate(files):
labels = np.loadtxt(file, dtype=np.float32).reshape(-1, 5)
if all(labels[:, 0] == 0):
print(labels.shape[0], file)
2019-07-19 23:28:29 +00:00
def select_best_evolve(path='evolve*.txt'): # from utils.utils import *; select_best_evolve()
2019-05-31 11:53:09 +00:00
# Find best evolved mutation
for file in sorted(glob.glob(path)):
2019-08-24 10:20:43 +00:00
x = np.loadtxt(file, dtype=np.float32, ndmin=2)
2019-09-10 09:52:27 +00:00
print(file, x[fitness(x).argmax()])
2019-05-31 11:53:09 +00:00
2019-10-08 17:07:28 +00:00
def crop_images_random(path='../images/', scale=0.50): # from utils.utils import *; crop_images_random()
# crops images into random squares up to scale fraction
# WARNING: overwrites images!
for file in tqdm(sorted(glob.glob('%s/*.*' % path))):
img = cv2.imread(file) # BGR
if img is not None:
h, w = img.shape[:2]
# create random mask
a = 30 # minimum size (pixels)
mask_h = random.randint(a, int(max(a, h * scale))) # mask height
mask_w = mask_h # mask width
# box
xmin = max(0, random.randint(0, w) - mask_w // 2)
ymin = max(0, random.randint(0, h) - mask_h // 2)
xmax = min(w, xmin + mask_w)
ymax = min(h, ymin + mask_h)
# apply random color mask
cv2.imwrite(file, img[ymin:ymax, xmin:xmax])
2019-08-03 20:51:19 +00:00
def coco_single_class_labels(path='../coco/labels/train2014/', label_class=43):
# Makes single-class coco datasets. from utils.utils import *; coco_single_class_labels()
if os.path.exists('new/'):
shutil.rmtree('new/') # delete output folder
os.makedirs('new/') # make new output folder
os.makedirs('new/labels/')
os.makedirs('new/images/')
for file in tqdm(sorted(glob.glob('%s/*.*' % path))):
with open(file, 'r') as f:
labels = np.array([x.split() for x in f.read().splitlines()], dtype=np.float32)
i = labels[:, 0] == label_class
if any(i):
img_file = file.replace('labels', 'images').replace('txt', 'jpg')
labels[:, 0] = 0 # reset class to 0
with open('new/images.txt', 'a') as f: # add image to dataset list
f.write(img_file + '\n')
with open('new/labels/' + Path(file).name, 'a') as f: # write label
for l in labels[i]:
f.write('%g %.6f %.6f %.6f %.6f\n' % tuple(l))
shutil.copyfile(src=img_file, dst='new/images/' + Path(file).name.replace('txt', 'jpg')) # copy images
2020-04-12 19:49:23 +00:00
def kmean_anchors(path='../coco/train2017.txt', n=12, img_size=(320, 1024), thr=0.10, gen=1000):
2020-04-10 23:34:32 +00:00
# Creates kmeans anchors for use in *.cfg files: from utils.utils import *; _ = kmean_anchors()
# n: number of anchors
# img_size: (min, max) image size used for multi-scale training (can be same values)
# thr: IoU threshold hyperparameter used for training (0.0 - 1.0)
2020-04-12 19:49:23 +00:00
# gen: generations to evolve anchors using genetic algorithm
2019-08-15 14:09:36 +00:00
from utils.datasets import LoadImagesAndLabels
2020-01-03 17:19:18 +00:00
2020-02-03 07:35:03 +00:00
def print_results(k):
2020-01-03 17:19:18 +00:00
k = k[np.argsort(k.prod(1))] # sort small to large
2020-02-03 07:35:03 +00:00
iou = wh_iou(wh, torch.Tensor(k))
2020-02-02 17:19:44 +00:00
max_iou = iou.max(1)[0]
2020-01-03 17:19:18 +00:00
bpr, aat = (max_iou > thr).float().mean(), (iou > thr).float().mean() * n # best possible recall, anch > thr
print('%.2f iou_thr: %.3f best possible recall, %.2f anchors > thr' % (thr, bpr, aat))
2020-02-02 17:19:44 +00:00
print('n=%g, img_size=%s, IoU_all=%.3f/%.3f-mean/best, IoU>thr=%.3f-mean: ' %
(n, img_size, iou.mean(), max_iou.mean(), iou[iou > thr].mean()), end='')
2020-01-03 17:19:18 +00:00
for i, x in enumerate(k):
print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg
return k
2020-02-03 07:35:03 +00:00
def fitness(k): # mutation fitness
2020-02-02 17:19:44 +00:00
iou = wh_iou(wh, torch.Tensor(k)) # iou
max_iou = iou.max(1)[0]
2020-04-09 04:01:58 +00:00
return (max_iou * (max_iou > thr).float()).mean() # product
2019-08-15 14:09:36 +00:00
# Get label wh
2019-12-30 21:28:32 +00:00
wh = []
2019-10-05 16:36:48 +00:00
dataset = LoadImagesAndLabels(path, augment=True, rect=True, cache_labels=True)
2020-01-02 19:09:10 +00:00
nr = 1 if img_size[0] == img_size[1] else 10 # number augmentation repetitions
2019-08-15 14:09:36 +00:00
for s, l in zip(dataset.shapes, dataset.labels):
2019-12-30 21:39:25 +00:00
wh.append(l[:, 3:5] * (s / s.max())) # image normalized to letterbox normalized wh
2020-01-02 19:09:10 +00:00
wh = np.concatenate(wh, 0).repeat(nr, axis=0) # augment 10x
2019-12-30 21:39:25 +00:00
wh *= np.random.uniform(img_size[0], img_size[1], size=(wh.shape[0], 1)) # normalized to pixels (multi-scale)
2020-02-02 17:19:44 +00:00
wh = wh[(wh > 2.0).all(1)] # remove below threshold boxes (< 2 pixels wh)
2019-08-15 14:09:36 +00:00
2020-01-03 17:19:18 +00:00
# Darknet yolov3.cfg anchors
2020-01-06 21:57:20 +00:00
use_darknet = False
2020-02-03 07:35:03 +00:00
if use_darknet and n == 9:
2020-01-03 17:19:18 +00:00
k = np.array([[10, 13], [16, 30], [33, 23], [30, 61], [62, 45], [59, 119], [116, 90], [156, 198], [373, 326]])
else:
# Kmeans calculation
from scipy.cluster.vq import kmeans
2020-01-04 19:36:36 +00:00
print('Running kmeans for %g anchors on %g points...' % (n, len(wh)))
2020-01-03 17:19:18 +00:00
s = wh.std(0) # sigmas for whitening
2020-01-06 21:59:08 +00:00
k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
2020-01-03 17:19:18 +00:00
k *= s
2020-02-03 07:35:03 +00:00
wh = torch.Tensor(wh)
k = print_results(k)
2019-08-15 14:09:36 +00:00
2019-11-22 23:38:28 +00:00
# # Plot
# k, d = [None] * 20, [None] * 20
# for i in tqdm(range(1, 21)):
2020-01-02 19:09:10 +00:00
# k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
2019-11-22 23:38:28 +00:00
# fig, ax = plt.subplots(1, 2, figsize=(14, 7))
# ax = ax.ravel()
# ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
2020-02-02 17:19:44 +00:00
# fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
# ax[0].hist(wh[wh[:, 0]<100, 0],400)
# ax[1].hist(wh[wh[:, 1]<100, 1],400)
# fig.tight_layout()
# fig.savefig('wh.png', dpi=200)
2019-11-22 23:38:28 +00:00
2020-01-03 17:19:18 +00:00
# Evolve
2020-01-29 22:18:45 +00:00
npr = np.random
2020-04-12 19:49:23 +00:00
f, sh, mp, s = fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
for _ in tqdm(range(gen), desc='Evolving anchors'):
2020-01-27 22:41:07 +00:00
v = np.ones(sh)
while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
2020-01-29 22:18:45 +00:00
v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0) # 98.6, 61.6
2020-01-27 21:52:40 +00:00
kg = (k.copy() * v).clip(min=2.0)
2020-02-03 07:35:03 +00:00
fg = fitness(kg)
2020-01-03 17:19:18 +00:00
if fg > f:
f, k = fg, kg.copy()
2020-02-03 07:35:03 +00:00
print_results(k)
k = print_results(k)
2020-01-03 17:19:18 +00:00
return k
2019-05-29 16:04:11 +00:00
2019-07-25 15:49:54 +00:00
def print_mutation(hyp, results, bucket=''):
# Print mutation results to evolve.txt (for use with train.py --evolve)
2019-08-24 14:43:43 +00:00
a = '%10s' * len(hyp) % tuple(hyp.keys()) # hyperparam keys
2019-09-10 11:17:05 +00:00
b = '%10.3g' * len(hyp) % tuple(hyp.values()) # hyperparam values
2020-01-04 20:26:02 +00:00
c = '%10.4g' * len(results) % results # results (P, R, mAP, F1, test_loss)
2019-07-25 15:49:54 +00:00
print('\n%s\n%s\nEvolved fitness: %s\n' % (a, b, c))
if bucket:
2020-01-14 04:59:59 +00:00
os.system('gsutil cp gs://%s/evolve.txt .' % bucket) # download evolve.txt
2019-08-11 17:16:54 +00:00
with open('evolve.txt', 'a') as f: # append result
f.write(c + b + '\n')
x = np.unique(np.loadtxt('evolve.txt', ndmin=2), axis=0) # load unique rows
2019-09-10 11:17:05 +00:00
np.savetxt('evolve.txt', x[np.argsort(-fitness(x))], '%10.3g') # save sort by fitness
2019-08-11 17:16:54 +00:00
if bucket:
2019-07-25 15:49:54 +00:00
os.system('gsutil cp evolve.txt gs://%s' % bucket) # upload evolve.txt
2019-10-10 20:54:20 +00:00
def apply_classifier(x, model, img, im0):
# applies a second stage classifier to yolo outputs
2020-01-15 18:22:59 +00:00
im0 = [im0] if isinstance(im0, np.ndarray) else im0
2019-10-10 20:54:20 +00:00
for i, d in enumerate(x): # per image
if d is not None and len(d):
d = d.clone()
# Reshape and pad cutouts
b = xyxy2xywh(d[:, :4]) # boxes
b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square
2019-10-11 23:18:41 +00:00
b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad
2019-10-10 20:54:20 +00:00
d[:, :4] = xywh2xyxy(b).long()
# Rescale boxes from img_size to im0 size
2020-01-09 22:07:55 +00:00
scale_coords(img.shape[2:], d[:, :4], im0[i].shape)
2019-10-10 20:54:20 +00:00
# Classes
2020-01-09 22:07:55 +00:00
pred_cls1 = d[:, 5].long()
2019-10-10 20:54:20 +00:00
ims = []
2019-10-12 11:59:07 +00:00
for j, a in enumerate(d): # per item
2020-01-09 22:07:55 +00:00
cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])]
2019-10-11 23:18:41 +00:00
im = cv2.resize(cutout, (224, 224)) # BGR
2019-10-12 11:59:07 +00:00
# cv2.imwrite('test%i.jpg' % j, cutout)
2019-10-10 20:54:20 +00:00
im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32
im /= 255.0 # 0 - 255 to 0.0 - 1.0
ims.append(im)
2019-10-12 11:59:07 +00:00
pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction
x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections
2019-10-10 20:54:20 +00:00
return x
2019-07-25 15:49:54 +00:00
def fitness(x):
# Returns fitness (for use with results.txt or evolve.txt)
2020-02-08 21:28:47 +00:00
w = [0.0, 0.01, 0.99, 0.00] # weights for [P, R, mAP, F1]@0.5 or [P, R, mAP@0.5, mAP@0.5:0.95]
2020-01-09 00:39:59 +00:00
return (x[:, :4] * w).sum(1)
2019-07-25 15:49:54 +00:00
2019-04-09 11:39:17 +00:00
# Plotting functions ---------------------------------------------------------------------------------------------------
def plot_one_box(x, img, color=None, label=None, line_thickness=None):
# Plots one bounding box on image img
2020-04-05 18:10:05 +00:00
tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness
2019-04-09 11:39:17 +00:00
color = color or [random.randint(0, 255) for _ in range(3)]
c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
cv2.rectangle(img, c1, c2, color, thickness=tl)
if label:
tf = max(tl - 1, 1) # font thickness
t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
cv2.rectangle(img, c1, c2, color, -1) # filled
cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
def plot_wh_methods(): # from utils.utils import *; plot_wh_methods()
# Compares the two methods for width-height anchor multiplication
# https://github.com/ultralytics/yolov3/issues/168
x = np.arange(-4.0, 4.0, .1)
ya = np.exp(x)
2019-04-06 14:13:11 +00:00
yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2
fig = plt.figure(figsize=(6, 3), dpi=150)
plt.plot(x, ya, '.-', label='yolo method')
plt.plot(x, yb ** 2, '.-', label='^2 power method')
plt.plot(x, yb ** 2.5, '.-', label='^2.5 power method')
plt.xlim(left=-4, right=4)
plt.ylim(bottom=0, top=6)
plt.xlabel('input')
plt.ylabel('output')
plt.legend()
fig.tight_layout()
2019-07-23 15:03:09 +00:00
fig.savefig('comparison.png', dpi=200)
def plot_images(imgs, targets, paths=None, fname='images.png'):
2019-04-09 10:24:32 +00:00
# Plots training images overlaid with targets
2019-04-09 11:21:39 +00:00
imgs = imgs.cpu().numpy()
targets = targets.cpu().numpy()
2019-07-09 16:16:15 +00:00
# targets = targets[targets[:, 1] == 21] # plot only one class
2019-04-09 11:21:39 +00:00
2019-04-09 10:24:01 +00:00
fig = plt.figure(figsize=(10, 10))
2019-04-25 20:47:31 +00:00
bs, _, h, w = imgs.shape # batch size, _, height, width
2019-07-20 17:27:27 +00:00
bs = min(bs, 16) # limit plot to 16 images
2019-04-25 20:47:31 +00:00
ns = np.ceil(bs ** 0.5) # number of subplots
2019-04-09 10:24:01 +00:00
for i in range(bs):
2019-04-25 20:47:31 +00:00
boxes = xywh2xyxy(targets[targets[:, 0] == i, 2:6]).T
boxes[[0, 2]] *= w
boxes[[1, 3]] *= h
plt.subplot(ns, ns, i + 1).imshow(imgs[i].transpose(1, 2, 0))
2019-07-09 16:16:35 +00:00
plt.plot(boxes[[0, 2, 2, 0, 0]], boxes[[1, 1, 3, 3, 1]], '.-')
2019-04-09 10:24:01 +00:00
plt.axis('off')
2019-07-07 21:24:34 +00:00
if paths is not None:
2019-07-07 21:53:56 +00:00
s = Path(paths[i]).name
plt.title(s[:min(len(s), 40)], fontdict={'size': 8}) # limit to 40 characters
2019-04-09 10:24:01 +00:00
fig.tight_layout()
2019-07-23 15:03:09 +00:00
fig.savefig(fname, dpi=200)
2019-04-09 10:32:26 +00:00
plt.close()
2019-04-09 10:24:01 +00:00
2019-06-22 17:21:05 +00:00
def plot_test_txt(): # from utils.utils import *; plot_test()
2019-06-01 16:29:14 +00:00
# Plot test.txt histograms
x = np.loadtxt('test.txt', dtype=np.float32)
box = xyxy2xywh(x[:, :4])
cx, cy = box[:, 0], box[:, 1]
fig, ax = plt.subplots(1, 1, figsize=(6, 6))
ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
ax.set_aspect('equal')
fig.tight_layout()
plt.savefig('hist2d.png', dpi=300)
2019-06-01 16:29:14 +00:00
fig, ax = plt.subplots(1, 2, figsize=(12, 6))
ax[0].hist(cx, bins=600)
ax[1].hist(cy, bins=600)
fig.tight_layout()
plt.savefig('hist1d.png', dpi=200)
2019-06-01 16:29:14 +00:00
2019-06-22 17:21:05 +00:00
def plot_targets_txt(): # from utils.utils import *; plot_targets_txt()
# Plot targets.txt histograms
x = np.loadtxt('targets.txt', dtype=np.float32).T
2019-06-23 20:01:11 +00:00
s = ['x targets', 'y targets', 'width targets', 'height targets']
2019-06-22 17:21:05 +00:00
fig, ax = plt.subplots(2, 2, figsize=(8, 8))
ax = ax.ravel()
for i in range(4):
ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std()))
ax[i].legend()
ax[i].set_title(s[i])
fig.tight_layout()
2019-07-23 15:03:09 +00:00
plt.savefig('targets.jpg', dpi=200)
2019-06-22 17:21:05 +00:00
2019-07-25 16:09:24 +00:00
def plot_evolution_results(hyp): # from utils.utils import *; plot_evolution_results(hyp)
2019-07-25 15:49:54 +00:00
# Plot hyperparameter evolution results in evolve.txt
2019-08-24 10:20:43 +00:00
x = np.loadtxt('evolve.txt', ndmin=2)
2019-07-25 15:49:54 +00:00
f = fitness(x)
weights = (f - f.min()) ** 2 # for weighted results
fig = plt.figure(figsize=(12, 10))
matplotlib.rc('font', **{'size': 8})
for i, (k, v) in enumerate(hyp.items()):
2019-11-14 21:14:47 +00:00
y = x[:, i + 7]
2019-07-25 15:49:54 +00:00
# mu = (y * weights).sum() / weights.sum() # best weighted result
mu = y[f.argmax()] # best single result
plt.subplot(4, 5, i + 1)
plt.plot(mu, f.max(), 'o', markersize=10)
plt.plot(y, f, '.')
2019-07-25 16:09:24 +00:00
plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
print('%15s: %.3g' % (k, mu))
2019-07-25 15:49:54 +00:00
fig.tight_layout()
plt.savefig('evolve.png', dpi=200)
2019-08-23 11:44:18 +00:00
def plot_results_overlay(start=0, stop=0): # from utils.utils import *; plot_results_overlay()
2019-08-05 11:32:48 +00:00
# Plot training results files 'results*.txt', overlaying train and val losses
2019-11-08 04:01:47 +00:00
s = ['train', 'train', 'train', 'Precision', 'mAP@0.5', 'val', 'val', 'val', 'Recall', 'F1'] # legends
2019-08-24 14:43:43 +00:00
t = ['GIoU', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles
2019-08-05 11:32:48 +00:00
for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
2019-08-24 14:43:43 +00:00
results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
2019-08-05 11:32:48 +00:00
n = results.shape[1] # number of rows
x = range(start, min(stop, n) if stop else n)
2019-08-05 13:40:40 +00:00
fig, ax = plt.subplots(1, 5, figsize=(14, 3.5))
ax = ax.ravel()
2019-08-05 11:32:48 +00:00
for i in range(5):
2019-08-05 14:59:32 +00:00
for j in [i, i + 5]:
2019-08-10 20:11:55 +00:00
y = results[j, x]
if i in [0, 1, 2]:
y[y == 0] = np.nan # dont show zero loss values
ax[i].plot(x, y, marker='.', label=s[j])
2019-08-05 11:32:48 +00:00
ax[i].set_title(t[i])
ax[i].legend()
2019-08-05 13:50:45 +00:00
ax[i].set_ylabel(f) if i == 0 else None # add filename
2019-08-05 13:40:40 +00:00
fig.tight_layout()
fig.savefig(f.replace('.txt', '.png'), dpi=200)
2019-08-05 11:32:48 +00:00
2019-12-14 23:15:20 +00:00
def plot_results(start=0, stop=0, bucket='', id=()): # from utils.utils import *; plot_results()
# Plot training 'results*.txt' as seen in https://github.com/ultralytics/yolov3#training
2020-02-21 23:10:50 +00:00
fig, ax = plt.subplots(2, 5, figsize=(12, 6))
2019-11-25 06:10:39 +00:00
ax = ax.ravel()
s = ['GIoU', 'Objectness', 'Classification', 'Precision', 'Recall',
'val GIoU', 'val Objectness', 'val Classification', 'mAP@0.5', 'F1']
2019-12-14 23:15:20 +00:00
if bucket:
2020-01-15 01:26:22 +00:00
os.system('rm -rf storage.googleapis.com')
2019-12-14 23:15:20 +00:00
files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]
else:
files = glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')
for f in sorted(files):
2020-04-11 18:04:10 +00:00
try:
results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
n = results.shape[1] # number of rows
x = range(start, min(stop, n) if stop else n)
for i in range(10):
y = results[i, x]
if i in [0, 1, 2, 5, 6, 7]:
y[y == 0] = np.nan # dont show zero loss values
# y /= y[0] # normalize
ax[i].plot(x, y, marker='.', label=Path(f).stem, linewidth=2, markersize=8)
ax[i].set_title(s[i])
if i in [5, 6, 7]: # share train and val loss y axes
ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
except:
print('Warning: Plotting error for %s, skipping file' % f)
2019-11-25 06:10:39 +00:00
fig.tight_layout()
ax[1].legend()
fig.savefig('results.png', dpi=200)