|
a |
|
b/utils/autoanchor.py |
|
|
1 |
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license |
|
|
2 |
""" |
|
|
3 |
AutoAnchor utils |
|
|
4 |
""" |
|
|
5 |
|
|
|
6 |
import random |
|
|
7 |
|
|
|
8 |
import numpy as np |
|
|
9 |
import torch |
|
|
10 |
import yaml |
|
|
11 |
from tqdm import tqdm |
|
|
12 |
|
|
|
13 |
from utils import TryExcept |
|
|
14 |
from utils.general import LOGGER, TQDM_BAR_FORMAT, colorstr |
|
|
15 |
|
|
|
16 |
PREFIX = colorstr('AutoAnchor: ') |
|
|
17 |
|
|
|
18 |
|
|
|
19 |
def check_anchor_order(m): |
|
|
20 |
# Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary |
|
|
21 |
a = m.anchors.prod(-1).mean(-1).view(-1) # mean anchor area per output layer |
|
|
22 |
da = a[-1] - a[0] # delta a |
|
|
23 |
ds = m.stride[-1] - m.stride[0] # delta s |
|
|
24 |
if da and (da.sign() != ds.sign()): # same order |
|
|
25 |
LOGGER.info(f'{PREFIX}Reversing anchor order') |
|
|
26 |
m.anchors[:] = m.anchors.flip(0) |
|
|
27 |
|
|
|
28 |
|
|
|
29 |
@TryExcept(f'{PREFIX}ERROR') |
|
|
30 |
def check_anchors(dataset, model, thr=4.0, imgsz=640): |
|
|
31 |
# Check anchor fit to data, recompute if necessary |
|
|
32 |
m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect() |
|
|
33 |
shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True) |
|
|
34 |
scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale |
|
|
35 |
wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh |
|
|
36 |
|
|
|
37 |
def metric(k): # compute metric |
|
|
38 |
r = wh[:, None] / k[None] |
|
|
39 |
x = torch.min(r, 1 / r).min(2)[0] # ratio metric |
|
|
40 |
best = x.max(1)[0] # best_x |
|
|
41 |
aat = (x > 1 / thr).float().sum(1).mean() # anchors above threshold |
|
|
42 |
bpr = (best > 1 / thr).float().mean() # best possible recall |
|
|
43 |
return bpr, aat |
|
|
44 |
|
|
|
45 |
stride = m.stride.to(m.anchors.device).view(-1, 1, 1) # model strides |
|
|
46 |
anchors = m.anchors.clone() * stride # current anchors |
|
|
47 |
bpr, aat = metric(anchors.cpu().view(-1, 2)) |
|
|
48 |
s = f'\n{PREFIX}{aat:.2f} anchors/target, {bpr:.3f} Best Possible Recall (BPR). ' |
|
|
49 |
if bpr > 0.98: # threshold to recompute |
|
|
50 |
LOGGER.info(f'{s}Current anchors are a good fit to dataset ✅') |
|
|
51 |
else: |
|
|
52 |
LOGGER.info(f'{s}Anchors are a poor fit to dataset ⚠️, attempting to improve...') |
|
|
53 |
na = m.anchors.numel() // 2 # number of anchors |
|
|
54 |
anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False) |
|
|
55 |
new_bpr = metric(anchors)[0] |
|
|
56 |
if new_bpr > bpr: # replace anchors |
|
|
57 |
anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors) |
|
|
58 |
m.anchors[:] = anchors.clone().view_as(m.anchors) |
|
|
59 |
check_anchor_order(m) # must be in pixel-space (not grid-space) |
|
|
60 |
m.anchors /= stride |
|
|
61 |
s = f'{PREFIX}Done ✅ (optional: update model *.yaml to use these anchors in the future)' |
|
|
62 |
else: |
|
|
63 |
s = f'{PREFIX}Done ⚠️ (original anchors better than new anchors, proceeding with original anchors)' |
|
|
64 |
LOGGER.info(s) |
|
|
65 |
|
|
|
66 |
|
|
|
67 |
def kmean_anchors(dataset='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True): |
|
|
68 |
""" Creates kmeans-evolved anchors from training dataset |
|
|
69 |
|
|
|
70 |
Arguments: |
|
|
71 |
dataset: path to data.yaml, or a loaded dataset |
|
|
72 |
n: number of anchors |
|
|
73 |
img_size: image size used for training |
|
|
74 |
thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0 |
|
|
75 |
gen: generations to evolve anchors using genetic algorithm |
|
|
76 |
verbose: print all results |
|
|
77 |
|
|
|
78 |
Return: |
|
|
79 |
k: kmeans evolved anchors |
|
|
80 |
|
|
|
81 |
Usage: |
|
|
82 |
from utils.autoanchor import *; _ = kmean_anchors() |
|
|
83 |
""" |
|
|
84 |
from scipy.cluster.vq import kmeans |
|
|
85 |
|
|
|
86 |
npr = np.random |
|
|
87 |
thr = 1 / thr |
|
|
88 |
|
|
|
89 |
def metric(k, wh): # compute metrics |
|
|
90 |
r = wh[:, None] / k[None] |
|
|
91 |
x = torch.min(r, 1 / r).min(2)[0] # ratio metric |
|
|
92 |
# x = wh_iou(wh, torch.tensor(k)) # iou metric |
|
|
93 |
return x, x.max(1)[0] # x, best_x |
|
|
94 |
|
|
|
95 |
def anchor_fitness(k): # mutation fitness |
|
|
96 |
_, best = metric(torch.tensor(k, dtype=torch.float32), wh) |
|
|
97 |
return (best * (best > thr).float()).mean() # fitness |
|
|
98 |
|
|
|
99 |
def print_results(k, verbose=True): |
|
|
100 |
k = k[np.argsort(k.prod(1))] # sort small to large |
|
|
101 |
x, best = metric(k, wh0) |
|
|
102 |
bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr |
|
|
103 |
s = f'{PREFIX}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr\n' \ |
|
|
104 |
f'{PREFIX}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' \ |
|
|
105 |
f'past_thr={x[x > thr].mean():.3f}-mean: ' |
|
|
106 |
for x in k: |
|
|
107 |
s += '%i,%i, ' % (round(x[0]), round(x[1])) |
|
|
108 |
if verbose: |
|
|
109 |
LOGGER.info(s[:-2]) |
|
|
110 |
return k |
|
|
111 |
|
|
|
112 |
if isinstance(dataset, str): # *.yaml file |
|
|
113 |
with open(dataset, errors='ignore') as f: |
|
|
114 |
data_dict = yaml.safe_load(f) # model dict |
|
|
115 |
from utils.dataloaders import LoadImagesAndLabels |
|
|
116 |
dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True) |
|
|
117 |
|
|
|
118 |
# Get label wh |
|
|
119 |
shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True) |
|
|
120 |
wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh |
|
|
121 |
|
|
|
122 |
# Filter |
|
|
123 |
i = (wh0 < 3.0).any(1).sum() |
|
|
124 |
if i: |
|
|
125 |
LOGGER.info(f'{PREFIX}WARNING ⚠️ Extremely small objects found: {i} of {len(wh0)} labels are <3 pixels in size') |
|
|
126 |
wh = wh0[(wh0 >= 2.0).any(1)].astype(np.float32) # filter > 2 pixels |
|
|
127 |
# wh = wh * (npr.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1 |
|
|
128 |
|
|
|
129 |
# Kmeans init |
|
|
130 |
try: |
|
|
131 |
LOGGER.info(f'{PREFIX}Running kmeans for {n} anchors on {len(wh)} points...') |
|
|
132 |
assert n <= len(wh) # apply overdetermined constraint |
|
|
133 |
s = wh.std(0) # sigmas for whitening |
|
|
134 |
k = kmeans(wh / s, n, iter=30)[0] * s # points |
|
|
135 |
assert n == len(k) # kmeans may return fewer points than requested if wh is insufficient or too similar |
|
|
136 |
except Exception: |
|
|
137 |
LOGGER.warning(f'{PREFIX}WARNING ⚠️ switching strategies from kmeans to random init') |
|
|
138 |
k = np.sort(npr.rand(n * 2)).reshape(n, 2) * img_size # random init |
|
|
139 |
wh, wh0 = (torch.tensor(x, dtype=torch.float32) for x in (wh, wh0)) |
|
|
140 |
k = print_results(k, verbose=False) |
|
|
141 |
|
|
|
142 |
# Plot |
|
|
143 |
# k, d = [None] * 20, [None] * 20 |
|
|
144 |
# for i in tqdm(range(1, 21)): |
|
|
145 |
# k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance |
|
|
146 |
# fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True) |
|
|
147 |
# ax = ax.ravel() |
|
|
148 |
# ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.') |
|
|
149 |
# fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh |
|
|
150 |
# ax[0].hist(wh[wh[:, 0]<100, 0],400) |
|
|
151 |
# ax[1].hist(wh[wh[:, 1]<100, 1],400) |
|
|
152 |
# fig.savefig('wh.png', dpi=200) |
|
|
153 |
|
|
|
154 |
# Evolve |
|
|
155 |
f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma |
|
|
156 |
pbar = tqdm(range(gen), bar_format=TQDM_BAR_FORMAT) # progress bar |
|
|
157 |
for _ in pbar: |
|
|
158 |
v = np.ones(sh) |
|
|
159 |
while (v == 1).all(): # mutate until a change occurs (prevent duplicates) |
|
|
160 |
v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0) |
|
|
161 |
kg = (k.copy() * v).clip(min=2.0) |
|
|
162 |
fg = anchor_fitness(kg) |
|
|
163 |
if fg > f: |
|
|
164 |
f, k = fg, kg.copy() |
|
|
165 |
pbar.desc = f'{PREFIX}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}' |
|
|
166 |
if verbose: |
|
|
167 |
print_results(k, verbose) |
|
|
168 |
|
|
|
169 |
return print_results(k).astype(np.float32) |