YOLO 目標檢測P/R/mAP計算方法


常見評價標准如Precision,Recall,AP,mAP的具體計算過程

評價指標

  • True positives: 簡稱為TP,即正樣本被正確識別為正樣本,飛機的圖片被正確的識別成了飛機。
  • True negatives: 簡稱為TN,即負樣本被正確識別為負樣本,大雁的圖片沒有被識別出來,系統正確地認為它們是大雁。
  • False Positives: 簡稱為FP,即負樣本被錯誤識別為正樣本,大雁的圖片被錯誤地識別成了飛機。
  • False negatives: 簡稱為FN,即正樣本被錯誤識別為負樣本,飛機的圖片沒有被識別出來,系統錯誤地認為它們是大雁。

評價標准

  • 准確率(Acc):准確率(Acc)的計算公式為,即預測正確的樣本比例,代表測試的樣本數。在檢測任務中沒有預測正確的負樣本的概念,所以Acc自然用不到了。
  • 查准率(Precision):查准率是針對某一個具體類別而言的,公式為:,其中N代表所有檢測到的某個具體類的目標框個數。
    -** 召回率(Recall)**:召回率仍然是針對某一個具體類別而言的,公式為:,即預測正確的目標框和所有Ground Truth框的比值。
  • F1 Score:定位Wie查准率和召回率的調和平均,公式如下:。
  • IOU:IoU是預測框與ground truth的交集和並集的比值。先為計算mAP值做一個鋪墊,即IOU閾值是如何影響Precision和Recall值的?比如在PASCAL VOC競賽中采用的IoU閾值為0.5,而COCO競賽中在計算mAP較復雜,其計算了一系列IoU閾值(0.05至0.95)下的mAP當成最后的mAP值。
  • mAP:全稱為Average Precision,AP值是Precision-Recall曲線下方的面積。那么問題來了,目標檢測中PR曲線怎么來的?可以在這篇論文找到答案,截圖如下:
    image

要得到Precision-Recall曲線(以下簡稱PR)曲線,首先要對檢測模型的預測結果按照目標置信度降序排列。然后給定一個rank值,Recall和Precision僅在置信度高於該rank值的預測結果中計算,改變rank值會相應的改變Recall值和Precision值。這里選擇了11個不同的rank值,也就得到了11組Precision和Recall值,然后AP值即定義為在這11個Recall下Precision值的平均值,其可以表征整個PR曲線下方的面積。即:
image

還有另外一種插值的計算方法,即對於某個Recall值r,Precision取所有Recall值大於r中的最大值,這樣保證了PR曲線是單調遞減的,避免曲線出現搖擺。另外需要注意的一點是在2010年后計算AP值時是取了所有的數據點,而不僅僅只是11個Recall值。我們在計算出AP之后,對所有類別求平均之后就是mAP值了,也是當前目標檢測用的最多的評判標准。

  • AP50,AP60,AP70等等代表什么意思?代表IOU閾值分別取0.5,0.6,0.7等對應的AP值。

代碼解析如下:

# --------------------------------------------------------
# Fast/er R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Bharath Hariharan
# --------------------------------------------------------

import xml.etree.ElementTree as ET #讀取xml文件
import os
import cPickle #序列化存儲模塊
import numpy as np

def parse_rec(filename):
    """ Parse a PASCAL VOC xml file """
    tree = ET.parse(filename)
    objects = []
    # 解析xml文件,將GT框信息放入一個列表
    for obj in tree.findall('object'):
        obj_struct = {}
        obj_struct['name'] = obj.find('name').text
        obj_struct['pose'] = obj.find('pose').text
        obj_struct['truncated'] = int(obj.find('truncated').text)
        obj_struct['difficult'] = int(obj.find('difficult').text)
        bbox = obj.find('bndbox')
        obj_struct['bbox'] = [int(bbox.find('xmin').text),
                              int(bbox.find('ymin').text),
                              int(bbox.find('xmax').text),
                              int(bbox.find('ymax').text)]
        objects.append(obj_struct)

    return objects

# 單個計算AP的函數,輸入參數為精確率和召回率,原理見上面
def voc_ap(rec, prec, use_07_metric=False):
    """ ap = voc_ap(rec, prec, [use_07_metric])
    Compute VOC AP given precision and recall.
    If use_07_metric is true, uses the
    VOC 07 11 point method (default:False).
    """
    # 如果使用2017年的計算AP的方式(插值的方式)
    if use_07_metric:
        # 11 point metric
        ap = 0.
        for t in np.arange(0., 1.1, 0.1):
            if np.sum(rec >= t) == 0:
                p = 0
            else:
                p = np.max(prec[rec >= t])
            ap = ap + p / 11.
    else:
       # 使用2010年后的計算AP值的方式
        # 這里是新增一個(0,0),方便計算
        mrec = np.concatenate(([0.], rec, [1.]))
        mpre = np.concatenate(([0.], prec, [0.]))

        # compute the precision envelope
        for i in range(mpre.size - 1, 0, -1):
            mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])

        # to calculate area under PR curve, look for points
        # where X axis (recall) changes value
        i = np.where(mrec[1:] != mrec[:-1])[0]

        # and sum (\Delta recall) * prec
        ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
    return ap

# 主函數
def voc_eval(detpath,
             annopath,
             imagesetfile,
             classname,
             cachedir,
             ovthresh=0.5,
             use_07_metric=False):
    """rec, prec, ap = voc_eval(detpath,
                                annopath,
                                imagesetfile,
                                classname,
                                [ovthresh],
                                [use_07_metric])
    Top level function that does the PASCAL VOC evaluation.
    detpath: 產生的txt文件,里面是一張圖片的各個檢測框結果。
    annopath: xml 文件與對應的圖像相呼應。
    imagesetfile: 一個txt文件,里面是每個圖片的地址,每行一個地址。
    classname: 種類的名字,即類別。
    cachedir: 緩存標注的目錄。
    [ovthresh]: IOU閾值,默認為0.5,即mAP50。
    [use_07_metric]: 是否使用2007的計算AP的方法,默認為Fasle
    """
    # assumes detections are in detpath.format(classname)
    # assumes annotations are in annopath.format(imagename)
    # assumes imagesetfile is a text file with each line an image name
    # cachedir caches the annotations in a pickle file

    # 首先加載Ground Truth標注信息。
    if not os.path.isdir(cachedir):
        os.mkdir(cachedir)
    # 即將新建文件的路徑
    cachefile = os.path.join(cachedir, 'annots.pkl')
    # 讀取文本里的所有圖片路徑
    with open(imagesetfile, 'r') as f:
        lines = f.readlines()
    # 獲取文件名,strip用來去除頭尾字符、空白符(包括\n、\r、\t、' ',即:換行、回車、制表符、空格)
    imagenames = [x.strip() for x in lines]
    #如果cachefile文件不存在,則寫入
    if not os.path.isfile(cachefile):
        # load annots
        recs = {}
        for i, imagename in enumerate(imagenames):
            #annopath.format(imagename): label的xml文件所在的路徑
            recs[imagename] = parse_rec(annopath.format(imagename))
            if i % 100 == 0:
                print 'Reading annotation for {:d}/{:d}'.format(
                    i + 1, len(imagenames))
        # save
        print 'Saving cached annotations to {:s}'.format(cachefile)
        with open(cachefile, 'w') as f:
            #寫入cPickle文件里面。寫入的是一個字典,左側為xml文件名,右側為文件里面個各個參數。
            cPickle.dump(recs, f)
    else:
        # load
        with open(cachefile, 'r') as f:
            recs = cPickle.load(f)

    # 對每張圖片的xml獲取函數指定類的bbox等
    class_recs = {}# 保存的是 Ground Truth的數據
    npos = 0
    for imagename in imagenames:
        # 獲取Ground Truth每個文件中某種類別的物體
        R = [obj for obj in recs[imagename] if obj['name'] == classname]
        bbox = np.array([x['bbox'] for x in R])
        #  different基本都為0/False
        difficult = np.array([x['difficult'] for x in R]).astype(np.bool)
        det = [False] * len(R)
        npos = npos + sum(~difficult) #自增,~difficult取反,統計樣本個數
        # # 記錄Ground Truth的內容
        class_recs[imagename] = {'bbox': bbox,
                                 'difficult': difficult,
                                 'det': det}

    # read dets 讀取某類別預測輸出
    detfile = detpath.format(classname)
    with open(detfile, 'r') as f:
        lines = f.readlines()

    splitlines = [x.strip().split(' ') for x in lines]
    image_ids = [x[0] for x in splitlines] # 圖片ID
    confidence = np.array([float(x[1]) for x in splitlines]) # IOU值
    BB = np.array([[float(z) for z in x[2:]] for x in splitlines]) # bounding box數值

    # 對confidence的index根據值大小進行降序排列。
    sorted_ind = np.argsort(-confidence)
    sorted_scores = np.sort(-confidence)
    #重排bbox,由大概率到小概率。
    BB = BB[sorted_ind, :]
    # 圖片重排,由大概率到小概率。
    image_ids = [image_ids[x] for x in sorted_ind]

    # go down dets and mark TPs and FPs
    nd = len(image_ids)
    tp = np.zeros(nd)
    fp = np.zeros(nd)
    for d in range(nd):
        R = class_recs[image_ids[d]]
        bb = BB[d, :].astype(float)
        ovmax = -np.inf
        BBGT = R['bbox'].astype(float)

        if BBGT.size > 0:
            # compute overlaps
            # intersection
            ixmin = np.maximum(BBGT[:, 0], bb[0])
            iymin = np.maximum(BBGT[:, 1], bb[1])
            ixmax = np.minimum(BBGT[:, 2], bb[2])
            iymax = np.minimum(BBGT[:, 3], bb[3])
            iw = np.maximum(ixmax - ixmin + 1., 0.)
            ih = np.maximum(iymax - iymin + 1., 0.)
            inters = iw * ih

            # union
            uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) +
                   (BBGT[:, 2] - BBGT[:, 0] + 1.) *
                   (BBGT[:, 3] - BBGT[:, 1] + 1.) - inters)

            overlaps = inters / uni
            ovmax = np.max(overlaps)
            jmax = np.argmax(overlaps)

        if ovmax > ovthresh:
            if not R['difficult'][jmax]:
                if not R['det'][jmax]:
                    tp[d] = 1.
                    R['det'][jmax] = 1
                else:
                    fp[d] = 1.
        else:
            fp[d] = 1.

    # compute precision recall
    fp = np.cumsum(fp)
    tp = np.cumsum(tp)
    rec = tp / float(npos)
    # avoid divide by zero in case the first detection matches a difficult
    # ground truth
    prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
    ap = voc_ap(rec, prec, use_07_metric)

	return rec, prec, ap


免責聲明!

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



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