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/autoanchor.py
Views: 475
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license1"""2Auto-anchor utils3"""45import random67import numpy as np8import torch9import yaml10from tqdm import tqdm1112from utils.general import LOGGER, colorstr, emojis13from utils.rboxs_utils import pi, poly2rbox, regular_theta14import cv21516PREFIX = colorstr('AutoAnchor: ')171819def check_anchor_order(m):20# Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary21a = m.anchors.prod(-1).view(-1) # anchor area22da = a[-1] - a[0] # delta a23ds = m.stride[-1] - m.stride[0] # delta s24if da.sign() != ds.sign(): # same order25LOGGER.info(f'{PREFIX}Reversing anchor order')26m.anchors[:] = m.anchors.flip(0)272829def check_anchors(dataset, model, thr=4.0, imgsz=640):30"""31Args:32Dataset.labels (list): n_imgs * array(num_gt_perimg, [cls_id, poly])33Dataset.shapes (array): (n_imgs, [ori_img_width, ori_img_height])34Returns:3536"""37# Check anchor fit to data, recompute if necessary38m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()39# shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)40min_ratios = imgsz / dataset.shapes.max(1, keepdims=True) #41scales = np.random.uniform(0.9, 1.1, size=(min_ratios.shape[0], 1)) # augment scale4243# wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh44ls_edges = []45for ratio, labels in zip(min_ratios * scales, dataset.labels): # labels (array): (num_gt_perimg, [cls_id, poly])46rboxes = poly2rbox(labels[:, 1:] * ratio)47if len(rboxes):48ls_edges.append(rboxes[:, 2:4])49ls_edges = torch.tensor(np.concatenate(ls_edges)).float()50ls_edges = ls_edges[(ls_edges >= 5.0).any(1)] # filter > 5 pixels, anchor 宽高不能都小于55152def metric(k): # compute metric53r = ls_edges[:, None] / k[None]54x = torch.min(r, 1 / r).min(2)[0] # ratio metric55best = x.max(1)[0] # best_x56aat = (x > 1 / thr).float().sum(1).mean() # anchors above threshold57bpr = (best > 1 / thr).float().mean() # best possible recall58return bpr, aat5960anchors = m.anchors.clone() * m.stride.to(m.anchors.device).view(-1, 1, 1) # current anchors61bpr, aat = metric(anchors.cpu().view(-1, 2))62s = f'\n{PREFIX}{aat:.2f} anchors/target, {bpr:.3f} Best Possible Recall (BPR). '63if bpr > 0.98: # threshold to recompute64LOGGER.info(emojis(f'{s}Current anchors are a good fit to dataset ✅'))65else:66LOGGER.info(emojis(f'{s}Anchors are a poor fit to dataset ⚠️, attempting to improve...'))67na = m.anchors.numel() // 2 # number of anchors68try:69anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)70except Exception as e:71LOGGER.info(f'{PREFIX}ERROR: {e}')72new_bpr = metric(anchors)[0]73if new_bpr > bpr: # replace anchors74anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)75m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss, featuremap stride pixel76check_anchor_order(m)77LOGGER.info(f'{PREFIX}New anchors saved to model. Update model *.yaml to use these anchors in the future.')78else:79LOGGER.info(f'{PREFIX}Original anchors better than new anchors. Proceeding with original anchors.')808182def kmean_anchors(dataset='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):83""" Creates kmeans-evolved anchors from training dataset8485Arguments:86dataset: path to data.yaml, or a loaded dataset87n: number of anchors88img_size: image size used for training89thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.090gen: generations to evolve anchors using genetic algorithm91verbose: print all results9293Return:94k: kmeans evolved anchors9596Usage:97from utils.autoanchor import *; _ = kmean_anchors()98"""99from scipy.cluster.vq import kmeans100101thr = 1 / thr102103def metric(k, wh): # compute metrics104r = wh[:, None] / k[None]105x = torch.min(r, 1 / r).min(2)[0] # ratio metric106# x = wh_iou(wh, torch.tensor(k)) # iou metric107return x, x.max(1)[0] # x, best_x108109def anchor_fitness(k): # mutation fitness110# _, best = metric(torch.tensor(k, dtype=torch.float32), wh)111_, best = metric(torch.tensor(k, dtype=torch.float32), ls_edges)112return (best * (best > thr).float()).mean() # fitness113114def print_results(k, verbose=True):115k = k[np.argsort(k.prod(1))] # sort small to large116# x, best = metric(k, wh0)117x, best = metric(k, ls_edges0)118bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr119s = f'{PREFIX}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr\n' \120f'{PREFIX}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' \121f'past_thr={x[x > thr].mean():.3f}-mean: '122for i, x in enumerate(k):123s += '%i,%i, ' % (round(x[0]), round(x[1]))124if verbose:125LOGGER.info(s[:-2])126return k127128if isinstance(dataset, str): # *.yaml file129with open(dataset, errors='ignore') as f:130data_dict = yaml.safe_load(f) # model dict131from utils.datasets import LoadImagesAndLabels132dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)133134# Get label l s135# shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)136# wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh137min_ratios = img_size / dataset.shapes.max(1, keepdims=True) #138ls_edges0 = []139for ratio, labels in zip(min_ratios, dataset.labels): # labels (array): (num_gt_perimg, [cls_id, poly])140rboxes = poly2rbox(labels[:, 1:] * ratio)141if len(rboxes):142ls_edges0.append(rboxes[:, 2:4])143ls_edges0 = np.concatenate(ls_edges0)144145# Filter146i = (ls_edges0 < 5.0).any(1).sum()147if i:148LOGGER.info(f'{PREFIX}WARNING: Extremely small objects found. {i} of {len(ls_edges0)} poly labels are < 5 pixels in size.')149# wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels150ls_edges = ls_edges0[(ls_edges0 >= 5.0).any(1)] # filter > 5 pixels151# wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1152153# Kmeans calculation154# LOGGER.info(f'{PREFIX}Running kmeans for {n} anchors on {len(wh)} points...')155# s = wh.std(0) # sigmas for whitening156# k, dist = kmeans(wh / s, n, iter=30) # points, mean distance157LOGGER.info(f'{PREFIX}Running kmeans for {n} anchors on {len(ls_edges)} points...')158s = ls_edges.std(0) # sigmas for whitening159k, dist = kmeans(ls_edges / s, n, iter=30) # points, mean distance160assert len(k) == n, f'{PREFIX}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}'161k *= s162# wh = torch.tensor(wh, dtype=torch.float32) # filtered163# wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered164ls_edges = torch.tensor(ls_edges, dtype=torch.float32) # filtered165ls_edges0 = torch.tensor(ls_edges0, dtype=torch.float32) # unfiltered166k = print_results(k, verbose=False)167168# Plot169# k, d = [None] * 20, [None] * 20170# for i in tqdm(range(1, 21)):171# k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance172# fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)173# ax = ax.ravel()174# ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')175# fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh176# ax[0].hist(wh[wh[:, 0]<100, 0],400)177# ax[1].hist(wh[wh[:, 1]<100, 1],400)178# fig.savefig('wh.png', dpi=200)179180# Evolve181npr = np.random182f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma183pbar = tqdm(range(gen), desc=f'{PREFIX}Evolving anchors with Genetic Algorithm:') # progress bar184for _ in pbar:185v = np.ones(sh)186while (v == 1).all(): # mutate until a change occurs (prevent duplicates)187v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)188kg = (k.copy() * v).clip(min=2.0)189fg = anchor_fitness(kg)190if fg > f:191f, k = fg, kg.copy()192pbar.desc = f'{PREFIX}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'193if verbose:194print_results(k, verbose)195196return print_results(k)197198199