car-detection-bayes/utils/utils.py

746 lines
29 KiB
Python
Raw Normal View History

2019-02-27 13:19:57 +00:00
import glob
2019-07-25 11:19:26 +00:00
import os
2018-08-26 08:51:39 +00:00
import random
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-05-29 16:04:11 +00:00
from PIL import Image
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
2018-08-26 08:51:39 +00:00
torch.set_printoptions(linewidth=1320, 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
2019-07-20 15:14:07 +00:00
def floatn(x, n=3): # format floats to n decimals
return float(format(x, '.%gf' % n))
2019-02-26 13:57:28 +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-05-05 11:44:12 +00:00
def model_info(model, report='summary'):
# Plots a line-by-line description of a PyTorch model
2018-11-22 12:52:22 +00:00
n_p = sum(x.numel() for x in model.parameters()) # number parameters
n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
2019-05-05 11:44:12 +00:00
if report is 'full':
print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))
for i, (name, p) in enumerate(model.named_parameters()):
name = name.replace('module_list.', '')
print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
(i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
print('Model Summary: %g layers, %g parameters, %g gradients' % (len(list(model.parameters())), n_p, n_g))
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
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
weights[weights == 0] = 1 # replace empty bins with 1
weights = 1 / weights # number of targets per class
weights /= weights.sum() # normalize
2019-04-27 15:44:26 +00:00
return torch.Tensor(weights)
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()
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')
# x = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
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
2018-08-26 08:51:39 +00:00
def weights_init_normal(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
torch.nn.init.normal_(m.weight.data, 0.0, 0.03)
elif classname.find('BatchNorm2d') != -1:
torch.nn.init.normal_(m.weight.data, 1.0, 0.03)
torch.nn.init.constant_(m.bias.data, 0.0)
2019-02-10 20:01:49 +00:00
def xyxy2xywh(x):
# Convert bounding box format from [x1, y1, x2, y2] to [x, y, w, h]
y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)
2018-09-02 09:15:39 +00:00
y[:, 0] = (x[:, 0] + x[:, 2]) / 2
y[:, 1] = (x[:, 1] + x[:, 3]) / 2
y[:, 2] = x[:, 2] - x[:, 0]
y[:, 3] = x[:, 3] - x[:, 1]
return y
2019-02-10 20:01:49 +00:00
def xywh2xyxy(x):
# Convert bounding box format from [x, y, w, h] to [x1, y1, x2, y2]
y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)
y[:, 0] = x[:, 0] - x[:, 2] / 2
y[:, 1] = x[:, 1] - x[:, 3] / 2
y[:, 2] = x[:, 0] + x[:, 2] / 2
y[:, 3] = x[:, 1] + x[:, 3] / 2
2018-09-02 09:15:39 +00:00
return y
2018-08-26 08:51:39 +00:00
2019-04-21 18:35:11 +00:00
def scale_coords(img1_shape, coords, img0_shape):
2019-07-15 14:27:13 +00:00
# Rescale coords (xyxy) from img1_shape to img0_shape
2019-04-22 12:59:39 +00:00
gain = max(img1_shape) / max(img0_shape) # gain = old / new
2019-04-22 14:52:14 +00:00
coords[:, [0, 2]] -= (img1_shape[1] - img0_shape[1] * gain) / 2 # x padding
coords[:, [1, 3]] -= (img1_shape[0] - img0_shape[0] * gain) / 2 # 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, 2]] = boxes[:, [0, 2]].clamp(min=0, max=img_shape[1]) # clip x
boxes[:, [1, 3]] = boxes[:, [1, 3]].clamp(min=0, max=img_shape[0]) # clip y
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
tp: True positives (list).
conf: Objectness value from 0-1 (list).
pred_cls: Predicted object classes (list).
target_cls: True object classes (list).
# 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
2018-11-22 12:52:22 +00:00
ap, p, r = [], [], []
2018-09-10 13:12:13 +00:00
for c in unique_classes:
i = pred_cls == c
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
if n_p == 0 and n_gt == 0:
2018-09-10 14:31:56 +00:00
continue
elif n_p == 0 or n_gt == 0:
2018-09-10 13:12:13 +00:00
ap.append(0)
2018-11-22 12:52:22 +00:00
r.append(0)
p.append(0)
2018-09-10 13:12:13 +00:00
else:
# Accumulate FPs and TPs
fpc = (1 - tp[i]).cumsum()
tpc = (tp[i]).cumsum()
2018-09-10 13:12:13 +00:00
# Recall
2018-11-22 12:52:22 +00:00
recall_curve = tpc / (n_gt + 1e-16)
2019-04-02 11:43:18 +00:00
r.append(recall_curve[-1])
2018-09-10 13:12:13 +00:00
# Precision
2018-11-22 12:52:22 +00:00
precision_curve = tpc / (tpc + fpc)
2019-04-02 11:43:18 +00:00
p.append(precision_curve[-1])
2018-09-10 13:12:13 +00:00
# AP from recall-precision curve
2018-11-22 12:52:22 +00:00
ap.append(compute_ap(recall_curve, precision_curve))
2018-09-10 13:12:13 +00:00
2019-04-02 11:43:18 +00:00
# Plot
# plt.plot(recall_curve, precision_curve)
2019-04-05 13:34:42 +00:00
# Compute F1 score (harmonic mean of precision and recall)
p, r, ap = np.array(p), np.array(r), np.array(ap)
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.
"""
# correct AP calculation
# first append sentinel values at the end
2018-09-10 13:12:13 +00:00
2018-08-26 08:51:39 +00:00
mrec = np.concatenate(([0.], recall, [1.]))
mpre = np.concatenate(([0.], precision, [0.]))
# compute the precision envelope
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
# to calculate area under PR curve, look for points
# where X axis (recall) changes value
i = np.where(mrec[1:] != mrec[:-1])[0]
# and sum (\Delta recall) * prec
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
return ap
2019-06-12 12:30:40 +00:00
def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=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
2018-08-26 08:51:39 +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]
2018-08-26 08:51:39 +00:00
else:
# x, y, w, h = box1
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
inter_area = (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
union_area = ((b1_x2 - b1_x1) * (b1_y2 - b1_y1) + 1e-16) + \
(b2_x2 - b2_x1) * (b2_y2 - b2_y1) - inter_area
2018-08-26 08:51:39 +00:00
2019-06-12 12:30:40 +00:00
iou = inter_area / union_area # iou
if GIoU: # Generalized IoU https://arxiv.org/pdf/1902.09630.pdf
c_x1, c_x2 = torch.min(b1_x1, b2_x1), torch.max(b1_x2, b2_x2)
c_y1, c_y2 = torch.min(b1_y1, b2_y1), torch.max(b1_y2, b2_y2)
c_area = (c_x2 - c_x1) * (c_y2 - c_y1) # convex area
return iou - (c_area - union_area) / c_area # GIoU
return iou
2018-08-26 08:51:39 +00:00
2018-09-09 14:14:24 +00:00
def wh_iou(box1, box2):
# Returns the IoU of wh1 to wh2. wh1 is 2, wh2 is nx2
box2 = box2.t()
2018-09-09 14:14:24 +00:00
# w, h = box1
w1, h1 = box1[0], box1[1]
w2, h2 = box2[0], box2[1]
2018-08-26 08:51:39 +00:00
# Intersection area
inter_area = torch.min(w1, w2) * torch.min(h1, h2)
2018-08-26 08:51:39 +00:00
# Union Area
union_area = (w1 * h1 + 1e-16) + w2 * h2 - inter_area
return inter_area / union_area # iou
2019-07-04 22:36:37 +00:00
def compute_loss(p, targets, model, giou_loss=True): # predictions, targets, model
2019-04-16 10:49:34 +00:00
ft = torch.cuda.FloatTensor if p[0].is_cuda else torch.Tensor
2019-07-04 20:10:46 +00:00
lxy, lwh, lcls, lobj = ft([0]), ft([0]), ft([0]), ft([0])
2019-07-12 10:23:17 +00:00
txy, twh, tcls, tbox, indices, anchor_vec = build_targets(model, targets)
2019-06-12 17:40:21 +00:00
h = model.hyp # hyperparameters
2019-04-17 13:52:51 +00:00
# Define criteria
2019-07-12 10:23:17 +00:00
MSE = nn.MSELoss()
BCEcls = nn.BCEWithLogitsLoss(pos_weight=ft([h['cls_pw']]))
BCEobj = nn.BCEWithLogitsLoss(pos_weight=ft([h['obj_pw']]))
2019-07-12 10:24:43 +00:00
# CE = nn.CrossEntropyLoss() # (weight=model.class_weights)
# Compute losses
2019-04-16 11:17:48 +00:00
bs = p[0].shape[0] # batch size
2019-07-12 10:23:17 +00:00
k = bs / 64 # loss gain
for i, pi0 in enumerate(p): # layer i predictions, i
2019-04-26 11:28:00 +00:00
b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
2019-07-04 20:10:46 +00:00
tobj = torch.zeros_like(pi0[..., 0]) # target obj
# Compute losses
2019-07-12 10:24:43 +00:00
nb = len(b)
if nb: # number of targets
pi = pi0[b, a, gj, gi] # predictions closest to anchors
2019-07-04 20:10:46 +00:00
tobj[b, a, gj, gi] = 1.0 # obj
2019-04-17 13:52:51 +00:00
# pi[..., 2:4] = torch.sigmoid(pi[..., 2:4]) # wh power loss (uncomment)
2019-07-25 16:18:40 +00:00
# s = 1.5 # scale_xy
pxy = torch.sigmoid(pi[..., 0:2]) # * s - (s - 1) / 2
2019-06-15 00:44:01 +00:00
if giou_loss:
2019-07-25 16:18:40 +00:00
pbox = torch.cat((pxy, torch.exp(pi[..., 2:4]) * anchor_vec[i]), 1) # predicted
2019-06-18 13:34:35 +00:00
giou = bbox_iou(pbox.t(), tbox[i], x1y1x2y2=False, GIoU=True) # giou computation
2019-07-12 10:23:17 +00:00
lxy += (k * h['giou']) * (1.0 - giou).mean() # giou loss
2019-06-15 00:44:01 +00:00
else:
2019-07-25 16:18:40 +00:00
lxy += (k * h['xy']) * MSE(pxy, txy[i]) # xy loss
2019-07-12 10:23:17 +00:00
lwh += (k * h['wh']) * MSE(pi[..., 2:4], twh[i]) # wh yolo loss
2019-06-25 10:37:24 +00:00
2019-07-12 10:24:43 +00:00
tclsm = torch.zeros_like(pi[..., 5:])
tclsm[range(nb), tcls[i]] = 1.0
lcls += (k * h['cls']) * BCEcls(pi[..., 5:], tclsm) # cls loss (BCE)
# lcls += (k * h['cls']) * CE(pi[..., 5:], tcls[i]) # cls loss (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)]
2019-07-12 10:23:17 +00:00
lobj += (k * h['obj']) * BCEobj(pi0[..., 4], tobj) # obj loss
2019-07-04 20:10:46 +00:00
loss = lxy + lwh + lobj + lcls
2019-07-04 20:10:46 +00:00
return loss, torch.cat((lxy, lwh, lobj, lcls, loss)).detach()
def build_targets(model, targets):
# targets = [image, class, x, y, w, h]
2019-04-18 00:13:04 +00:00
iou_thres = model.hyp['iou_t'] # hyperparameter
2019-04-11 10:47:35 +00:00
if type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel):
model = model.module
nt = len(targets)
2019-06-12 12:30:40 +00:00
txy, twh, tcls, tbox, indices, anchor_vec = [], [], [], [], [], []
2019-04-11 10:41:07 +00:00
for i in model.yolo_layers:
layer = model.module_list[i][0]
# iou of targets-anchors
t, a = targets, []
2019-07-04 20:50:03 +00:00
gwh = t[:, 4:6] * layer.ng
if nt:
2019-07-04 20:50:03 +00:00
iou = torch.stack([wh_iou(x, gwh) for x in layer.anchor_vec], 0)
2019-07-04 22:36:37 +00:00
use_best_anchor = False
if use_best_anchor:
2019-07-04 20:50:03 +00:00
iou, a = iou.max(0) # best iou and anchor
2019-07-04 22:36:37 +00:00
else: # use all anchors
2019-07-04 20:50:03 +00:00
na = len(layer.anchor_vec) # number of anchors
a = torch.arange(na).view((-1, 1)).repeat([1, nt]).view(-1)
t = targets.repeat([na, 1])
gwh = gwh.repeat([na, 1])
iou = iou.view(-1) # use all ious
2019-07-04 22:36:37 +00:00
# reject anchors below iou_thres (OPTIONAL, increases P, lowers R)
reject = True
if reject:
2019-04-18 00:13:04 +00:00
j = iou > iou_thres
2019-07-04 20:50:03 +00:00
t, a, gwh = t[j], a[j], gwh[j]
# Indices
2019-03-31 17:57:44 +00:00
b, c = t[:, :2].long().t() # target image, class
2019-04-26 11:28:00 +00:00
gxy = t[:, 2:4] * layer.ng # grid x, y
gi, gj = gxy.long().t() # grid x, y indices
indices.append((b, a, gj, gi))
2018-08-26 08:51:39 +00:00
2019-02-19 21:19:59 +00:00
# XY coordinates
2019-06-12 12:30:40 +00:00
gxy -= gxy.floor()
txy.append(gxy)
# GIoU
tbox.append(torch.cat((gxy, gwh), 1)) # xywh (grids)
anchor_vec.append(layer.anchor_vec[a])
2018-09-20 16:03:19 +00:00
2019-02-19 21:19:59 +00:00
# Width and height
2019-04-10 14:51:58 +00:00
twh.append(torch.log(gwh / layer.anchor_vec[a])) # wh yolo method
# twh.append((gwh / layer.anchor_vec[a]) ** (1 / 3) / 2) # wh power method
2018-08-26 08:51:39 +00:00
# Class
tcls.append(c)
2019-04-12 12:58:19 +00:00
if c.shape[0]:
2019-04-19 18:41:18 +00:00
assert c.max() <= layer.nc, 'Target classes exceed model classes'
2018-08-26 08:51:39 +00:00
2019-07-12 10:23:17 +00:00
return txy, twh, tcls, tbox, indices, anchor_vec
2018-08-26 08:51:39 +00:00
2019-04-09 14:28:14 +00:00
def non_max_suppression(prediction, conf_thres=0.5, nms_thres=0.5):
2018-08-26 08:51:39 +00:00
"""
2019-02-18 16:48:35 +00:00
Removes detections with lower object confidence score than 'conf_thres'
2018-08-26 08:51:39 +00:00
Non-Maximum Suppression to further filter detections.
Returns detections with shape:
(x1, y1, x2, y2, object_conf, class_conf, class)
2018-08-26 08:51:39 +00:00
"""
min_wh = 2 # (pixels) minimum box width and height
output = [None] * len(prediction)
2018-08-26 08:51:39 +00:00
for image_i, pred in enumerate(prediction):
2019-01-02 15:32:38 +00:00
# Experiment: Prior class size rejection
# x, y, w, h = pred[:, 0], pred[:, 1], pred[:, 2], pred[:, 3]
# a = w * h # area
# ar = w / (h + 1e-16) # aspect ratio
2018-08-26 08:51:39 +00:00
# n = len(w)
2019-01-02 15:32:38 +00:00
# log_w, log_h, log_a, log_ar = torch.log(w), torch.log(h), torch.log(a), torch.log(ar)
2018-08-26 08:51:39 +00:00
# shape_likelihood = np.zeros((n, 60), dtype=np.float32)
# x = np.concatenate((log_w.reshape(-1, 1), log_h.reshape(-1, 1)), 1)
# from scipy.stats import multivariate_normal
# for c in range(60):
2019-02-11 17:15:51 +00:00
# shape_likelihood[:, c] =
# multivariate_normal.pdf(x, mean=mat['class_mu'][c, :2], cov=mat['class_cov'][c, :2, :2])
2018-08-26 08:51:39 +00:00
2019-04-13 18:11:08 +00:00
# Multiply conf by class conf to get combined confidence
class_conf, class_pred = pred[:, 5:].max(1)
2019-04-02 20:54:32 +00:00
pred[:, 4] *= class_conf
2018-08-26 08:51:39 +00:00
2019-04-13 18:11:08 +00:00
# Select only suitable predictions
2019-04-24 14:39:56 +00:00
i = (pred[:, 4] > conf_thres) & (pred[:, 2:4] > min_wh).all(1) & torch.isfinite(pred).all(1)
pred = pred[i]
2018-08-26 08:51:39 +00:00
# If none are remaining => process next image
if len(pred) == 0:
2018-08-26 08:51:39 +00:00
continue
# Select predicted classes
class_conf = class_conf[i]
class_pred = class_pred[i].unsqueeze(1).float()
# Box (center x, center y, width, height) to (x1, y1, x2, y2)
2018-12-19 22:48:52 +00:00
pred[:, :4] = xywh2xyxy(pred[:, :4])
2019-04-02 20:54:32 +00:00
# pred[:, 4] *= class_conf # improves mAP from 0.549 to 0.551
# Detections ordered as (x1y1x2y2, obj_conf, class_conf, class_pred)
pred = torch.cat((pred[:, :5], class_conf.unsqueeze(1), class_pred), 1)
2018-08-26 08:51:39 +00:00
# Get detections sorted by decreasing confidence scores
pred = pred[(-pred[:, 4]).argsort()]
det_max = []
2019-07-08 13:28:29 +00:00
nms_style = 'MERGE' # 'OR' (default), 'AND', 'MERGE' (experimental)
for c in pred[:, -1].unique():
dc = pred[pred[:, -1] == c] # select class c
2019-04-24 15:13:36 +00:00
n = len(dc)
if n == 1:
det_max.append(dc) # No NMS required if only 1 prediction
2019-04-12 12:00:16 +00:00
continue
2019-04-24 15:13:36 +00:00
elif n > 100:
dc = dc[:100] # limit to first 100 boxes: https://github.com/ultralytics/yolov3/issues/117
2019-04-12 12:00:16 +00:00
2019-02-18 17:32:31 +00:00
# Non-maximum suppression
2019-02-27 11:52:02 +00:00
if nms_style == 'OR': # default
# METHOD1
# ind = list(range(len(dc)))
# while len(ind):
# j = ind[0]
# det_max.append(dc[j:j + 1]) # save highest conf detection
# reject = (bbox_iou(dc[j], dc[ind]) > nms_thres).nonzero()
# [ind.pop(i) for i in reversed(reject)]
# METHOD2
while dc.shape[0]:
det_max.append(dc[:1]) # save highest conf detection
if len(dc) == 1: # Stop if we're at the last detection
break
iou = bbox_iou(dc[0], dc[1:]) # iou with other boxes
dc = dc[1:][iou < nms_thres] # remove ious > threshold
2019-02-18 18:13:40 +00:00
2019-02-18 17:32:31 +00:00
elif nms_style == 'AND': # requires overlap, single boxes erased
while len(dc) > 1:
iou = bbox_iou(dc[0], dc[1:]) # iou with other boxes
2019-02-18 17:32:31 +00:00
if iou.max() > 0.5:
det_max.append(dc[:1])
dc = dc[1:][iou < nms_thres] # remove ious > threshold
elif nms_style == 'MERGE': # weighted mixture box
while len(dc):
2019-04-12 12:00:16 +00:00
if len(dc) == 1:
det_max.append(dc)
break
i = bbox_iou(dc[0], dc) > nms_thres # iou with other boxes
weights = dc[i, 4:5]
2019-02-18 18:13:40 +00:00
dc[0, :4] = (weights * dc[i, :4]).sum(0) / weights.sum()
det_max.append(dc[:1])
dc = dc[i == 0]
2018-08-26 08:51:39 +00:00
2019-05-02 21:56:58 +00:00
elif nms_style == 'SOFT': # soft-NMS https://arxiv.org/abs/1704.04503
2019-05-02 22:26:26 +00:00
sigma = 0.5 # soft-nms sigma parameter
2019-05-02 21:56:58 +00:00
while len(dc):
if len(dc) == 1:
det_max.append(dc)
break
det_max.append(dc[:1])
iou = bbox_iou(dc[0], dc[1:]) # iou with other boxes
dc = dc[1:]
dc[:, 4] *= torch.exp(-iou ** 2 / sigma) # decay confidences
2019-07-08 13:52:13 +00:00
# dc = dc[dc[:, 4] > nms_thres] # new line per https://github.com/ultralytics/yolov3/issues/362
2019-05-02 21:56:58 +00:00
if len(det_max):
det_max = torch.cat(det_max) # concatenate
output[image_i] = det_max[(-det_max[:, 4]).argsort()] # sort
2018-08-26 08:51:39 +00:00
return output
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
2018-10-26 22:42:34 +00:00
def strip_optimizer_from_checkpoint(filename='weights/best.pt'):
2018-08-26 08:51:39 +00:00
# Strip optimizer from *.pt files for lighter files (reduced by 2/3 size)
a = torch.load(filename, map_location='cpu')
a['optimizer'] = []
torch.save(a, filename.replace('.pt', '_lite.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-02-20 14:11:55 +00:00
def coco_only_people(path='../coco/labels/val2014/'):
# 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)):
x = np.loadtxt(file, dtype=np.float32)
2019-07-19 23:28:29 +00:00
fitness = x[:, 2] * 0.5 + x[:, 3] * 0.5 # weighted mAP and F1 combination
print(file, x[fitness.argmax()])
2019-05-31 11:53:09 +00:00
2019-07-25 11:23:39 +00:00
def kmeans_targets(path='./data/coco_64img.txt', n=9, img_size=320): # from utils.utils import *; kmeans_targets()
# Produces a list of target kmeans suitable for use in *.cfg files
2019-07-25 11:19:26 +00:00
img_formats = ['.bmp', '.jpg', '.jpeg', '.png', '.tif']
2019-05-29 16:04:11 +00:00
with open(path, 'r') as f:
2019-07-25 11:19:26 +00:00
img_files = [x for x in f.read().splitlines() if os.path.splitext(x)[-1].lower() in img_formats]
2019-05-29 16:04:11 +00:00
# Read shapes
2019-07-25 11:23:39 +00:00
nf = len(img_files)
assert nf > 0, 'No images found in %s' % path
2019-07-25 11:19:26 +00:00
label_files = [x.replace('images', 'labels').replace(os.path.splitext(x)[-1], '.txt') for x in img_files]
2019-05-29 16:04:11 +00:00
s = np.array([Image.open(f).size for f in tqdm(img_files, desc='Reading image shapes')]) # (width, height)
# Read targets
2019-07-25 11:23:39 +00:00
labels = [np.zeros((0, 5))] * nf
2019-05-29 16:04:11 +00:00
iter = tqdm(label_files, desc='Reading labels')
for i, file in enumerate(iter):
try:
with open(file, 'r') as f:
l = np.array([x.split() for x in f.read().splitlines()], dtype=np.float32)
if l.shape[0]:
assert l.shape[1] == 5, '> 5 label columns: %s' % file
assert (l >= 0).all(), 'negative labels: %s' % file
assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels: %s' % file
l[:, [1, 3]] *= s[i][0]
l[:, [2, 4]] *= s[i][1]
2019-07-25 11:23:39 +00:00
l[:, 1:] *= img_size / max(s[i]) # nominal img_size for training here
2019-05-29 16:04:11 +00:00
labels[i] = l
except:
pass # print('Warning: missing labels for %s' % self.img_files[i]) # missing label file
assert len(np.concatenate(labels, 0)) > 0, 'No labels found. Incorrect label paths provided.'
2019-07-25 11:23:39 +00:00
# kmeans calculation
2019-05-29 16:04:11 +00:00
from scipy import cluster
wh = np.concatenate(labels, 0)[:, 3:5]
2019-07-25 11:23:39 +00:00
k = cluster.vq.kmeans(wh, n)[0]
2019-05-29 16:04:11 +00:00
k = k[np.argsort(k.prod(1))]
for x in k.ravel():
2019-07-25 11:37:01 +00:00
print('%.1f, ' % x, end='') # drop-in replacement for *.cfg anchors
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)
a = '%11s' * len(hyp) % tuple(hyp.keys()) # hyperparam keys
b = '%11.3g' * len(hyp) % tuple(hyp.values()) # hyperparam values
c = '%11.3g' * len(results) % results # results (P, R, mAP, F1, test_loss)
print('\n%s\n%s\nEvolved fitness: %s\n' % (a, b, c))
if bucket:
os.system('gsutil cp gs://%s/evolve.txt .' % bucket) # download evolve.txt
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
np.savetxt('evolve.txt', x[np.argsort(-fitness(x))], '%11.3g') # save sort by fitness
os.system('gsutil cp evolve.txt gs://%s' % bucket) # upload evolve.txt
else:
with open('evolve.txt', 'a') as f:
f.write(c + b + '\n')
def fitness(x):
# Returns fitness (for use with results.txt or evolve.txt)
2019-07-26 21:55:11 +00:00
return 0.50 * x[:, 2] + 0.50 * x[:, 3] # fitness = 0.9 * mAP + 0.1 * F1
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
2019-07-15 14:27:13 +00:00
tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line 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)
2019-07-07 21:24:34 +00:00
def plot_images(imgs, targets, paths=None, fname='images.jpg'):
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.jpg', dpi=300)
fig, ax = plt.subplots(1, 2, figsize=(12, 6))
ax[0].hist(cx, bins=600)
ax[1].hist(cy, bins=600)
fig.tight_layout()
2019-07-23 15:03:09 +00:00
plt.savefig('hist1d.jpg', 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 test.txt histograms
x = np.loadtxt('targets.txt', dtype=np.float32)
x = x.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
x = np.loadtxt('evolve.txt')
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()):
y = x[:, i + 5]
# 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-05-11 12:38:48 +00:00
def plot_results(start=0, stop=0): # from utils.utils import *; plot_results()
2019-04-01 18:27:11 +00:00
# Plot training results files 'results*.txt'
# import os; os.system('wget https://storage.googleapis.com/ultralytics/yolov3/results_v3.txt')
2019-01-02 15:32:38 +00:00
2019-04-18 20:31:05 +00:00
fig, ax = plt.subplots(2, 5, figsize=(14, 7))
ax = ax.ravel()
2019-07-16 16:06:24 +00:00
s = ['GIoU/XY', 'Width/Height', 'Confidence', 'Classification', 'Train Loss', 'Precision', 'Recall', 'mAP', 'F1',
2019-04-05 13:34:42 +00:00
'Test Loss']
2019-04-17 12:57:39 +00:00
for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
2019-04-05 13:34:42 +00:00
results = np.loadtxt(f, usecols=[2, 3, 4, 5, 6, 9, 10, 11, 12, 13]).T
2019-04-11 10:21:33 +00:00
n = results.shape[1] # number of rows
x = range(start, min(stop, n) if stop else n)
2019-04-05 13:34:42 +00:00
for i in range(10):
2019-04-18 20:31:05 +00:00
ax[i].plot(x, results[i, x], marker='.', label=f.replace('.txt', ''))
ax[i].set_title(s[i])
fig.tight_layout()
2019-04-27 19:38:20 +00:00
ax[4].legend()
2019-07-23 15:03:09 +00:00
fig.savefig('results.png', dpi=200)