CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hukaixuan19970627

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: hukaixuan19970627/yolov5_obb
Path: blob/master/utils/autoanchor.py
Views: 475
1
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
"""
3
Auto-anchor 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.general import LOGGER, colorstr, emojis
14
from utils.rboxs_utils import pi, poly2rbox, regular_theta
15
import cv2
16
17
PREFIX = colorstr('AutoAnchor: ')
18
19
20
def check_anchor_order(m):
21
# Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
22
a = m.anchors.prod(-1).view(-1) # anchor area
23
da = a[-1] - a[0] # delta a
24
ds = m.stride[-1] - m.stride[0] # delta s
25
if da.sign() != ds.sign(): # same order
26
LOGGER.info(f'{PREFIX}Reversing anchor order')
27
m.anchors[:] = m.anchors.flip(0)
28
29
30
def check_anchors(dataset, model, thr=4.0, imgsz=640):
31
"""
32
Args:
33
Dataset.labels (list): n_imgs * array(num_gt_perimg, [cls_id, poly])
34
Dataset.shapes (array): (n_imgs, [ori_img_width, ori_img_height])
35
Returns:
36
37
"""
38
# Check anchor fit to data, recompute if necessary
39
m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
40
# shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
41
min_ratios = imgsz / dataset.shapes.max(1, keepdims=True) #
42
scales = np.random.uniform(0.9, 1.1, size=(min_ratios.shape[0], 1)) # augment scale
43
44
# wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
45
ls_edges = []
46
for ratio, labels in zip(min_ratios * scales, dataset.labels): # labels (array): (num_gt_perimg, [cls_id, poly])
47
rboxes = poly2rbox(labels[:, 1:] * ratio)
48
if len(rboxes):
49
ls_edges.append(rboxes[:, 2:4])
50
ls_edges = torch.tensor(np.concatenate(ls_edges)).float()
51
ls_edges = ls_edges[(ls_edges >= 5.0).any(1)] # filter > 5 pixels, anchor 宽高不能都小于5
52
53
def metric(k): # compute metric
54
r = ls_edges[:, None] / k[None]
55
x = torch.min(r, 1 / r).min(2)[0] # ratio metric
56
best = x.max(1)[0] # best_x
57
aat = (x > 1 / thr).float().sum(1).mean() # anchors above threshold
58
bpr = (best > 1 / thr).float().mean() # best possible recall
59
return bpr, aat
60
61
anchors = m.anchors.clone() * m.stride.to(m.anchors.device).view(-1, 1, 1) # current anchors
62
bpr, aat = metric(anchors.cpu().view(-1, 2))
63
s = f'\n{PREFIX}{aat:.2f} anchors/target, {bpr:.3f} Best Possible Recall (BPR). '
64
if bpr > 0.98: # threshold to recompute
65
LOGGER.info(emojis(f'{s}Current anchors are a good fit to dataset ✅'))
66
else:
67
LOGGER.info(emojis(f'{s}Anchors are a poor fit to dataset ⚠️, attempting to improve...'))
68
na = m.anchors.numel() // 2 # number of anchors
69
try:
70
anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
71
except Exception as e:
72
LOGGER.info(f'{PREFIX}ERROR: {e}')
73
new_bpr = metric(anchors)[0]
74
if new_bpr > bpr: # replace anchors
75
anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
76
m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss, featuremap stride pixel
77
check_anchor_order(m)
78
LOGGER.info(f'{PREFIX}New anchors saved to model. Update model *.yaml to use these anchors in the future.')
79
else:
80
LOGGER.info(f'{PREFIX}Original anchors better than new anchors. Proceeding with original anchors.')
81
82
83
def kmean_anchors(dataset='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
84
""" Creates kmeans-evolved anchors from training dataset
85
86
Arguments:
87
dataset: path to data.yaml, or a loaded dataset
88
n: number of anchors
89
img_size: image size used for training
90
thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
91
gen: generations to evolve anchors using genetic algorithm
92
verbose: print all results
93
94
Return:
95
k: kmeans evolved anchors
96
97
Usage:
98
from utils.autoanchor import *; _ = kmean_anchors()
99
"""
100
from scipy.cluster.vq import kmeans
101
102
thr = 1 / thr
103
104
def metric(k, wh): # compute metrics
105
r = wh[:, None] / k[None]
106
x = torch.min(r, 1 / r).min(2)[0] # ratio metric
107
# x = wh_iou(wh, torch.tensor(k)) # iou metric
108
return x, x.max(1)[0] # x, best_x
109
110
def anchor_fitness(k): # mutation fitness
111
# _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
112
_, best = metric(torch.tensor(k, dtype=torch.float32), ls_edges)
113
return (best * (best > thr).float()).mean() # fitness
114
115
def print_results(k, verbose=True):
116
k = k[np.argsort(k.prod(1))] # sort small to large
117
# x, best = metric(k, wh0)
118
x, best = metric(k, ls_edges0)
119
bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
120
s = f'{PREFIX}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr\n' \
121
f'{PREFIX}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' \
122
f'past_thr={x[x > thr].mean():.3f}-mean: '
123
for i, x in enumerate(k):
124
s += '%i,%i, ' % (round(x[0]), round(x[1]))
125
if verbose:
126
LOGGER.info(s[:-2])
127
return k
128
129
if isinstance(dataset, str): # *.yaml file
130
with open(dataset, errors='ignore') as f:
131
data_dict = yaml.safe_load(f) # model dict
132
from utils.datasets import LoadImagesAndLabels
133
dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
134
135
# Get label l s
136
# shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
137
# wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
138
min_ratios = img_size / dataset.shapes.max(1, keepdims=True) #
139
ls_edges0 = []
140
for ratio, labels in zip(min_ratios, dataset.labels): # labels (array): (num_gt_perimg, [cls_id, poly])
141
rboxes = poly2rbox(labels[:, 1:] * ratio)
142
if len(rboxes):
143
ls_edges0.append(rboxes[:, 2:4])
144
ls_edges0 = np.concatenate(ls_edges0)
145
146
# Filter
147
i = (ls_edges0 < 5.0).any(1).sum()
148
if i:
149
LOGGER.info(f'{PREFIX}WARNING: Extremely small objects found. {i} of {len(ls_edges0)} poly labels are < 5 pixels in size.')
150
# wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels
151
ls_edges = ls_edges0[(ls_edges0 >= 5.0).any(1)] # filter > 5 pixels
152
# wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1
153
154
# Kmeans calculation
155
# LOGGER.info(f'{PREFIX}Running kmeans for {n} anchors on {len(wh)} points...')
156
# s = wh.std(0) # sigmas for whitening
157
# k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
158
LOGGER.info(f'{PREFIX}Running kmeans for {n} anchors on {len(ls_edges)} points...')
159
s = ls_edges.std(0) # sigmas for whitening
160
k, dist = kmeans(ls_edges / s, n, iter=30) # points, mean distance
161
assert len(k) == n, f'{PREFIX}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}'
162
k *= s
163
# wh = torch.tensor(wh, dtype=torch.float32) # filtered
164
# wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered
165
ls_edges = torch.tensor(ls_edges, dtype=torch.float32) # filtered
166
ls_edges0 = torch.tensor(ls_edges0, dtype=torch.float32) # unfiltered
167
k = print_results(k, verbose=False)
168
169
# Plot
170
# k, d = [None] * 20, [None] * 20
171
# for i in tqdm(range(1, 21)):
172
# k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
173
# fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
174
# ax = ax.ravel()
175
# ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
176
# fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
177
# ax[0].hist(wh[wh[:, 0]<100, 0],400)
178
# ax[1].hist(wh[wh[:, 1]<100, 1],400)
179
# fig.savefig('wh.png', dpi=200)
180
181
# Evolve
182
npr = np.random
183
f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
184
pbar = tqdm(range(gen), desc=f'{PREFIX}Evolving anchors with Genetic Algorithm:') # progress bar
185
for _ in pbar:
186
v = np.ones(sh)
187
while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
188
v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
189
kg = (k.copy() * v).clip(min=2.0)
190
fg = anchor_fitness(kg)
191
if fg > f:
192
f, k = fg, kg.copy()
193
pbar.desc = f'{PREFIX}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'
194
if verbose:
195
print_results(k, verbose)
196
197
return print_results(k)
198
199