1. 程式人生 > >MAP評價指標在faster-rcnn中的使用

MAP評價指標在faster-rcnn中的使用

Mean Average Precision(MAP):平均精度均值

1.MAP可以由它的三個部分來理解:P,AP,MAP

P(Precision)精度,正確率。在資訊檢索領域用的比較多,和正確率一塊出現的是召回率Recall。對於一個查詢,返回了一系列的文件,正確率指的是返回的結果中相關的文件佔的比例,定義為:
precision=返回結果中相關文件的數目/返回結果的數目
而召回率則是返回結果中相關文件佔所有相關文件的比例,定義為:Recall=返回結果中相關文件的數目/所有相關文件的數目。

從數學公式理解:
混淆矩陣
True Positive(真正,TP):將正類預測為正類數
True Negative(真負,TN):將負類預測為負類數
False Positive(假正,FP):將負類預測為正類數誤報 (Type I error)
False Negative(假負,FN):將正類預測為負類數→漏報 (Type II error)
準確率(Accuracy)

:ACC=(TP+TN)/(Tp+TN+FP+FN)
精確率(precision):P=TP/(TP+FP)(分類後的結果中正類的佔比)
召回率(recall):recall=TP/(TP+FN)(所有正例被分對的比例)

應用於影象識別:
有一個兩類分類問題,分別5個樣本,如果這個分類器效能達到完美的話,ranking結果應該是+1,+1,+1,+1,+1,-1,-1,-1,-1,-1.

但是分類器預測的label,和實際的score肯定不會這麼完美。按照從大到小來打分,我們可以計算兩個指標:precisionrecall。比如分類器認為打分由高到低選擇了前四個,實際上這裡面只有兩個是正樣本。此時的recall就是2(你能包住的正樣本數)/5(總共的正樣本數)=0.4,precision是2(你選對了的)/4(總共選的)=0.5.

影象分類中,這個打分score可以由SVM得到:s=w^Tx+b就是每一個樣本的分數。

從上面的例子可以看出,其實precision,recall都是選多少個樣本k的函式,很容易想到,如果我總共有1000個樣本,那麼我就可以像這樣計算1000對P-R,並且把他們畫出來,這就是PR曲線:

這裡有一個趨勢,recall越高,precision越低。這是很合理的,因為假如說我把1000個全拿進來,那肯定正樣本都包住了,recall=1,但是此時precision就很小了,因為我全部認為他們是正樣本。recall=1時的precision的數值,等於正樣本所佔的比例。

平均精度AP(average precision):

就是PR曲線下的面積,這裡average,等於是對recall取平均。而mean average precision的mean,是對所有類別取平均(每一個類當做一次二分類任務)。現在的影象分類論文基本都是用mAP作為標準。
AP是把準確率在recall值為Recall = {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1}時(總共11個rank水平上),求平均值:

AP = 1/11 ∑ recall∈{0,0.1,…,1} Precision(Recall)

均精度均值(mAP):只是把每個類別的AP都算了一遍,再取平均值:

mAP = AVG(AP for each object class)

因此,AP是針對單個類別的,mAP是針對所有類別的。

在影象識別具體應用方法如下:

  1. 對於類別C,首先將演算法輸出的所有C類別的預測框,按置信度排序;
  2. 選擇top k個預測框,計算FP和TP,使得recall 等於1;
  3. 計算Precision;
  4. 重複2步驟,選擇不同的k,使得recall分別等於0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0;
  5. 將得到的11個Precision取平均,即得到AP; AP是針對單一類別的,mAP是將所有類別的AP求和,再取平均:
         mAP = 所有類別的AP之和 / 類別的總個數

2.faster-rcnn的MAP程式碼解析

Faster R-CNN/ R-FCN在github上的python原始碼用mAP來度量模型的效能。mAP是各類別AP的平均,而各類別AP值是該類別precision(prec)對該類別recall(rec)的積分得到的,即PR曲線下面積,這裡主要從程式碼角度看一下pascal_voc.pyvoc_eval.py裡關於AP,rec, prec的實現。
畫出PR曲線,只需要在pascal_voc.py新增幾行程式碼即可:
1.檔案頭部新增庫:

import matplotlib.pyplot as plt
import pylab as pl
from sklearn.metrics import precision_recall_curve
from itertools import cycle

2._do_python_eval函式新增

def _do_python_eval(self, output_dir='output'):
    annopath = os.path.join(
      self._devkit_path,
      'VOC' + self._year,
      'Annotations',
      '{:s}.xml')
    imagesetfile = os.path.join(
      self._devkit_path,
      'VOC' + self._year,
      'ImageSets',
      'Main',
      self._image_set + '.txt')
    cachedir = os.path.join(self._devkit_path, 'annotations_cache')
    aps = []
    # The PASCAL VOC metric changed in 2010
    use_07_metric = True if int(self._year) < 2010 else False
    print('VOC07 metric? ' + ('Yes' if use_07_metric else 'No'))
    if not os.path.isdir(output_dir):
      os.mkdir(output_dir)
    for i, cls in enumerate(self._classes):
      if cls == '__background__':
        continue
      filename = self._get_voc_results_file_template().format(cls)
      rec, prec, ap = voc_eval(
        filename, annopath, imagesetfile, cls, cachedir, ovthresh=0.5,
        use_07_metric=use_07_metric)
      aps += [ap]
      #畫圖,這裡的rec以及prec是由函式voc_eval得到
      pl.plot(rec, prec, lw=2, 
              label='Precision-recall curve of class {} (area = {:.4f})'
                    ''.format(cls, ap))
      print(('AP for {} = {:.4f}'.format(cls, ap)))
      with open(os.path.join(output_dir, cls + '_pr.pkl'), 'wb') as f:
        pickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f)
 #以下為畫圖程式
    pl.xlabel('Recall')
    pl.ylabel('Precision')
    plt.grid(True)
    pl.ylim([0.0, 1.05])
    pl.xlim([0.0, 1.0])
    pl.title('Precision-Recall')
    pl.legend(loc="upper right")     
    plt.show()
 #畫圖完畢
    print(('Mean AP = {:.4f}'.format(np.mean(aps))))
    print('~~~~~~~~')
    print('Results:')
    for ap in aps:
      print(('{:.3f}'.format(ap)))
    print(('{:.3f}'.format(np.mean(aps))))
    print('~~~~~~~~')
    print('')
    print('--------------------------------------------------------------')
    print('Results computed with the **unofficial** Python eval code.')
    print('Results should be very close to the official MATLAB eval code.')
    print('Recompute with `./tools/reval.py --matlab ...` for your paper.')
    print('-- Thanks, The Management')
    print('--------------------------------------------------------------')

函式voc_eval在lib/datasets/voc_eval.py中,詳細分析如下:

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

import xml.etree.ElementTree as ET
import os
import cPickle
import numpy as np

def parse_rec(filename): #讀取標註的xml檔案
    """ Parse a PASCAL VOC xml file """
    tree = ET.parse(filename)
    objects = []
    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

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).
    計算AP值,若use_07_metric=true,則用11個點取樣的方法,將rec從0-1分成11個點,這些點prec值求平均近似表示AP
    若use_07_metric=false,則採用更為精確的逐點積分方法
    """
    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:
        # correct AP calculation
        # first append sentinel values at the end
        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,  ######主函式,計算當前類別的recall和precision
             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檔案,路徑VOCdevkit/results/VOC20xx/Main/<comp_id>_det_test_aeroplane.txt。
    """該檔案格式:imagename1 confidence xmin ymin xmax ymax  (影象1的第一個結果)
                   imagename1 confidence xmin ymin xmax ymax  (影象1的第二個結果)
                   imagename1 confidence xmin ymin xmax ymax  (影象2的第一個結果)
                   ......
        每個結果佔一行,檢測到多少個BBox就有多少行,這裡假設有20000個檢測結果
    """
    detpath: Path to detections
        detpath.format(classname) should produce the detection results file.
    annopath: Path to annotations
        annopath.format(imagename) should be the xml annotations file. #xml 標註檔案。
    imagesetfile: Text file containing the list of images, one image per line. #資料集劃分txt檔案,路徑VOCdevkit/VOC20xx/ImageSets/Main/test.txt這裡假設測試影象1000張,那麼該txt檔案1000行。
    classname: Category name (duh) #種類的名字,即類別,假設類別2(一類目標+背景)。
    cachedir: Directory for caching the annotations #快取標註的目錄路徑VOCdevkit/annotation_cache,影象資料只讀檔案,為了避免每次都要重新讀資料集原始資料。
    [ovthresh]: Overlap threshold (default = 0.5) #重疊的多少大小。
    [use_07_metric]: Whether to use VOC07's 11 point AP computation 
        (default False) #是否使用VOC07的AP計算方法,voc07是11個點取樣。
    """
    # 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

    # first load gt 載入ground truth。
    if not os.path.isdir(cachedir):
        os.mkdir(cachedir)
    cachefile = os.path.join(cachedir, 'annots.pkl') #只讀檔名稱。
    # read list of images
    with open(imagesetfile, 'r') as f:
        lines = f.readlines() #讀取所有待檢測圖片名。
    imagenames = [x.strip() for x in lines] #待檢測影象檔名字存於陣列imagenames,長度1000。

    if not os.path.isfile(cachefile): #如果只讀檔案不存在,則只好從原始資料集中重新載入資料
        # load annots
        recs = {}
        for i, imagename in enumerate(imagenames):
            recs[imagename] = parse_rec(annopath.format(imagename)) #parse_rec函式讀取當前影象標註檔案,返回當前影象標註,存於recs字典(key是影象名,values是gt)
            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.dump(recs, f) #recs字典c儲存到只讀檔案。
    else:
        # load
        with open(cachefile, 'r') as f:
            recs = cPickle.load(f) #如果已經有了只讀檔案,載入到recs。

    # extract gt objects for this class #按類別獲取標註檔案,recall和precision都是針對不同類別而言的,AP也是對各個類別分別算的。
    class_recs = {} #當前類別的標註
    npos = 0 #npos標記的目標數量
    for imagename in imagenames:
        R = [obj for obj in recs[imagename] if obj['name'] == classname] #過濾,只保留recs中指定類別的項,存為R。
        bbox = np.array([x['bbox'] for x in R]) #抽取bbox
        difficult = np.array([x['difficult'] for x in R]).astype(np.bool) #如果資料集沒有difficult,所有項都是0.

        det = [False] * len(R) #len(R)就是當前類別的gt目標個數,det表示是否檢測到,初始化為false。
        npos = npos + sum(~difficult) #自增,非difficult樣本數量,如果資料集沒有difficult,npos數量就是gt數量。
        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] #假設檢測結果有20000個,則splitlines長度20000
    image_ids = [x[0] for x in splitlines] #檢測結果中的影象名,image_ids長度20000,但實際影象只有1000張,因為一張影象上可以有多個目標檢測結果
    confidence = np.array([float(x[1]) for x in splitlines]) #檢測結果置信度
    BB = np.array([[float(z) for z in x[2:]] for x in splitlines]) #變為浮點型的bbox。

    # sort by confidence 將20000各檢測結果按置信度排序
    sorted_ind = np.argsort(-confidence) #對confidence的index根據值大小進行降序排列。
    sorted_scores = np.sort(-confidence) #降序排列。
    BB = BB[sorted_ind, :] #重排bbox,由大概率到小概率。
    image_ids = [image_ids[x] for x in sorted_ind] 對image_ids相應地進行重排。

    # go down dets and mark TPs and FPs 
    nd = len(image_ids) #注意這裡是20000,不是1000
    tp = np.zeros(nd) # true positive,長度20000
    fp = np.zeros(nd) # false positive,長度20000
    for d in range(nd): #遍歷所有檢測結果,因為已經排序,所以這裡是從置信度最高到最低遍歷
        R = class_recs[image_ids[d]] #當前檢測結果所在影象的所有同類別gt
        bb = BB[d, :].astype(float) #當前檢測結果bbox座標
        ovmax = -np.inf
        BBGT = R['bbox'].astype(float) #當前檢測結果所在影象的所有同類別gt的bbox座標

        if BBGT.size > 0: 
            # compute overlaps 計算當前檢測結果,與該檢測結果所在影象的標註重合率,一對多用到python的broadcast機制
            # 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)#最大重合率對應的gt

        if ovmax > ovthresh:#如果當前檢測結果與真實標註最大重合率滿足閾值
            if not R['difficult'][jmax]:
                if not R['det'][jmax]:
                    tp[d] = 1. #正檢數目+1
                    R['det'][jmax] = 1 #該gt被置為已檢測到,下一次若還有另一個檢測結果與之重合率滿足閾值,則不能認為多檢測到一個目標
                else: #相反,認為檢測到一個虛警
                    fp[d] = 1.
        else: #不滿足閾值,肯定是虛警
            fp[d] = 1.

    # compute precision recall
    fp = np.cumsum(fp) #積分圖,在當前節點前的虛警數量,fp長度
    tp = np.cumsum(tp) #積分圖,在當前節點前的正檢數量
    rec = tp / float(npos) #召回率,長度20000,從0到1
    # avoid divide by zero in case the first detection matches a difficult
    # ground truth 準確率,長度20000,長度20000,從1到0
    prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
    ap = voc_ap(rec, prec, use_07_metric)

    return rec, prec, ap