yolov5 自適應 anchor


yolov5 自適應 anchor

anchor(錨框)

在 yolos.yaml 文件中

anchors:
  - [10,13, 16,30, 33,23]  # P3/8
  - [30,61, 62,45, 59,119]  # P4/16
  - [116,90, 156,198, 373,326]  # P5/32

之前在 yolov5s.yaml 增加一個檢測頭和 anchor , 對anchor的應用理解並不是很深刻
只知道,為了對小目標適應力,增加了一個小目標的 anchors [5,6,8,15,15,11]

anchors參數里面共9個數值,一共三行9列,每一行代表在不同的特征圖上,
比如第一行是在最大的特征圖上的錨框,
第二行是在中間的特征圖上的錨框,
第三行是在最小的特征圖上的錨框,
每一行后面的注釋是 特征圖的大小, 如P3/8:當前特征圖的大小為P3/8
對於目標檢測的任務來說,我們一般希望在更大的特征圖上去檢測小目標,這樣的大特征圖才含有更多的小目標信息。

事實上 不同的目標檢測算法的錨框設置有很大區別, 不同的數據集標注所對的錨框也有區別

設置自動計算

設置位置:
trian.py

parser.add_argument('--noautoanchor',default='True', action='store_true', help='disable autoanchor check')

trian.py

        if not opt.noautoanchor:
            check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz)

源代碼

檢測 anchors參數 是否符合

yolov5-master\utils\autoanchor.py

def check_anchors(dataset, model, thr=4.0, imgsz=640):
    """
        參數dataset代表的是訓練集,
        hyp['anchor_t']這個超參數是一個界定anchor與label匹配程度的閾值,
        imgsz自然就是網絡輸入尺寸
    
    """
    # Check anchor fit to data, recompute if necessary
    prefix = colorstr('autoanchor: ')
    print(f'\n{prefix}Analyzing anchors... ', end='')
    m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1]  # Detect()
    shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
    scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1))  # augment scale
    wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float()  
    # wh

    def metric(k):  # compute metric
        r = wh[:, None] / k[None]
        x = torch.min(r, 1. / r).min(2)[0]  # ratio metric
        best = x.max(1)[0]  # best_x
        aat = (x > 1. / thr).float().sum(1).mean()  # anchors above threshold
        bpr = (best > 1. / thr).float().mean()  # best possible recall
        return bpr, aat

    anchors = m.anchor_grid.clone().cpu().view(-1, 2)  # current anchors
    bpr, aat = metric(anchors)
    print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='')
    if bpr < 0.98:  # threshold to recompute
        print('. Attempting to improve anchors, please wait...')
        na = m.anchor_grid.numel() // 2  # number of anchors
        try:
            anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
        except Exception as e:
            print(f'{prefix}ERROR: {e}')
        new_bpr = metric(anchors)[0]
        if new_bpr > bpr:  # replace anchors
            anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
            m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid)  # for inference
            m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1)  # loss
            check_anchor_order(m)
            print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.')
        else:
            print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.')
    print('')  # newline

yolov5模型中 只有當bpr小於0.98時才會重新計算anchor
具體計算bpr(best possible recall)的時候,會考慮這9類anchor的寬高和gt框的寬高之間的差距

    def metric(k):  # compute metric
        r = wh[:, None] / k[None]
        x = torch.min(r, 1. / r).min(2)[0]  # ratio metric
        best = x.max(1)[0]  # best_x
        aat = (x > 1. / thr).float().sum(1).mean()  # anchors above threshold
        bpr = (best > 1. / thr).float().mean()  # best possible recall
        return bpr, aat

變量wh用來存儲訓練數據中所有gt框的寬高,是一個shape為(N,2)的tensor,N為gt框的總的個數
輸入k是一個shape為 (9,2) 表示 anchors的寬和高兩個維度

通過anchor和wh來計算bpr,aat(anchors above threshold) 兩個指標,來判斷是否滿足

  • bpr(best possible recall): 最多能被召回的gt框數量 / 所有gt框數量 最大值為1 越大越好 小於0.98就需要使用k-means + 遺傳進化算法選擇出與數據集更匹配的anchors框。

wh[:, None]的shape是[N, 2]變[N, 1, 2]
k[None]的shape是[9,2]變[1, 9, 2]
x = torch.min(r, 1. / r).min(2)[0]
無論r大於1,還是小於等於1最后統一結果都要小於1
x的shape[N,9]
best的shape是[N]

重新計算

重新計算新的 anchors 框參數
使用 kmeans 對自定義數據進行分析,重新計算 anchors ,獲得適合自定義數據集中對象邊界框預測的預設錨定框。


def kmean_anchors(dataset='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
    """ Creates kmeans-evolved anchors from training dataset

        Arguments:
            dataset: path to data.yaml, or a loaded dataset
            n: number of anchors
            img_size: image size used for training
            thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0, 長寬比閾值
            gen: generations to evolve anchors using genetic algorithm, 產生 anchors 迭代次數
            verbose: print all results

        Return:
            k: kmeans evolved anchors
            返回聚類后的數據結果
        Usage:
            from utils.autoanchor import *; _ = kmean_anchors()
    """
    
    from scipy.cluster.vq import kmeans

    thr = 1. / thr
    prefix = colorstr('autoanchor: ')

    def metric(k, wh):  # compute metrics
        r = wh[:, None] / k[None]
        x = torch.min(r, 1. / r).min(2)[0]  # ratio metric
        # x = wh_iou(wh, torch.tensor(k))  # iou metric
        return x, x.max(1)[0]  # x, best_x

    def anchor_fitness(k):  # mutation fitness
        _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
        return (best * (best > thr).float()).mean()  # fitness

    def print_results(k):
        k = k[np.argsort(k.prod(1))]  # sort small to large
        x, best = metric(k, wh0)
        bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n  # best possible recall, anch > thr
        print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr')
        print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, '
              f'past_thr={x[x > thr].mean():.3f}-mean: ', end='')
        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

    if isinstance(dataset, str):  # *.yaml file
        with open(dataset, errors='ignore') as f:
            data_dict = yaml.safe_load(f)  # model dict
        from utils.datasets import LoadImagesAndLabels
        dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)

    # Get label wh
    shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
    wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)])  # wh

    # Filter
    i = (wh0 < 3.0).any(1).sum()
    if i:
        print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.')
    wh = wh0[(wh0 >= 2.0).any(1)]  # filter > 2 pixels
    # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1)  # multiply by random scale 0-1

    # Kmeans calculation
    print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...')
    s = wh.std(0)  # sigmas for whitening
    k, dist = kmeans(wh / s, n, iter=30)  # points, mean distance
    assert len(k) == n, print(f'{prefix}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}')
    k *= s
    wh = torch.tensor(wh, dtype=torch.float32)  # filtered
    wh0 = torch.tensor(wh0, dtype=torch.float32)  # unfiltered
    k = print_results(k)

    # Plot
    # k, d = [None] * 20, [None] * 20
    # for i in tqdm(range(1, 21)):
    #     k[i-1], d[i-1] = kmeans(wh / s, i)  # points, mean distance
    # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
    # ax = ax.ravel()
    # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
    # 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.savefig('wh.png', dpi=200)

    # Evolve
    npr = np.random
    f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1  # fitness, generations, mutation prob, sigma
    pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:')  # progress bar
    for _ in pbar:
        v = np.ones(sh)
        while (v == 1).all():  # mutate until a change occurs (prevent duplicates)
            v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
        kg = (k.copy() * v).clip(min=2.0)
        fg = anchor_fitness(kg)
        if fg > f:
            f, k = fg, kg.copy()
            pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'
            if verbose:
                print_results(k)

    return print_results(k)

主要思想是 將圖像轉化到resize640大小的長寬比下,再進行kmeans 聚類,得到9個聚類中心,每個聚類中的包含(x,y)坐標就是需要的 anchor

主要流程

  1. 載入數據集,得到數據集中所有數據的wh
  2. 將每張圖片中wh的最大值等比例縮放到指定大小img_size,較小邊也相應縮放
  3. 將bboxes從相對坐標改成絕對坐標(乘以縮放后的wh)
  4. 篩選bboxes,保留wh都大於等於兩個像素的bboxes
  5. 使用k-means聚類得到n個anchors(掉k-means包 涉及一個白化操作)
  6. 使用遺傳算法隨機對anchors的wh進行變異,如果變異后效果變得更好(使用anchor_fitness方法計算得到的fitness(適應度)進行評估)就將變異后的結果賦值給anchors,如果變異后效果變差就跳過,默認變異1000次
參考博客:1、https://blog.csdn.net/aabbcccddd01/article/details/109578614

參考博客:2、(推薦) https://blog.csdn.net/qq_38253797/article/details/119713706?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_title~default-1.no_search_link&spm=1001.2101.3001.4242


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM