YOLOv5中autoanchor.py的def metric(k)的r = wh[:, None] / k[None]的理解
生活随笔
收集整理的這篇文章主要介紹了
YOLOv5中autoanchor.py的def metric(k)的r = wh[:, None] / k[None]的理解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
check_anchors()內metric()函數
def check_anchors(dataset, model, thr=4.0, imgsz=640):"""在train.py中調用,計算BPR確定是否需要改變anchors 需要就調用K-means重新計算anchorsargs: dataset -> 自定義數據集LoadImagesAndLabels返回的數據集model -> 初始化的模型thr -> 超參數,界定anchor與label匹配程度的閾值,anchor與標簽框的比例范圍為(1/thr, thr),在此范圍內算是滿足要求imgsz -> 輸入圖片尺寸,默認640"""# Check anchor fit to data, recompute if necessary# 打印字符串:autoanchor:Analyzing anchors...prefix = colorstr('autoanchor: ')print(f'\n{prefix}Analyzing anchors... ', end='')# 取出模型最后一層,即Detect層m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()# dataset.shapes.max(1, keepdims=True) = 每張圖片的較長邊# shapes: 將數據集圖片的最長邊縮放到img_size, 較小邊相應縮放,得到新的所有數據集圖片shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)# 產生隨機數scale [2501, 1]scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale# 將GT的歸一化坐標縮放為基于圖片大小為shapes * scale的坐標wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # whdef metric(k): # compute metric"""根據wh計算anchor是否滿足要求,即anchor與標簽框的比值要在(1/thr, thr)args:k -> 一般傳入的是anchors的寬高 [M, 2],也可傳入GT的寬高wh: [N, 2],M為anchor的數量,作者M取9,N為GT的數量return:bpr -> best possible recall 最多能被召回(通過thr)的gt框數量/所有gt框數量,小于0.98 才會用k-means計算anchoraat -> anchors above threshold 每個target平均有多少個anchors"""r = wh[:, None] / k[None]# x:高寬比和寬高比的最小值,無論r大于1,還是小于等于1,最后統一結果都要小于1 [N, M]x = torch.min(r, 1. / r).min(2)[0] # ratio metricbest = x.max(1)[0] # best_xaat = (x > 1. / thr).float().sum(1).mean() # anchors above thresholdbpr = (best > 1. / thr).float().mean() # best possible recallreturn bpr, aat
None用以添加維度,所有GT的wh[:, None],[N, 2]->[N, 1, 2],所有anchor的wh k[None] [M, 2]->[1, M, 2]
r: GT的寬高與anchor的寬高的比值,即h/h_a, w/w_a,r.shape=(N, M, 2),r中元素有可能大于1,也可能小于等于1
為什么要添加維度:原來的維度是[N, 2]、[M, 2],無法相除,因為不滿足廣播機制,但是增加維度后就可以滿足了廣播原則的條件
總結
以上是生活随笔為你收集整理的YOLOv5中autoanchor.py的def metric(k)的r = wh[:, None] / k[None]的理解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 美团token解决思路
- 下一篇: 和平精英怎么在电脑上玩?匹配手机最简单的