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

猜你喜欢

转载自blog.csdn.net/ff_xun/article/details/82354999