Detection基础模块之(二)mAP

1.mAP及相关概念

关于PR曲线、Precision、Recall、TP、FP、FN等概念的细节可参考机器学习评价指标合辑

关于IoU的概念和实现可参考IoU

  • mAP: mean Average Precision, 即各类别AP的平均值

  • AP: PR曲线下面积,其实是在0~1之间所有recall值的precision的平均值。

  • PR曲线: Precision-Recall曲线

  • Precision: TP / (TP + FP)

  • Recall: TP / (TP + FN)

  • TP: IoU>Threshold的检测框数量(同一Ground Truth只计算一次)

  • FP: IoU<=Threshold的检测框,或者是检测到同一个GT的多余检测框的数量

  • FN: 没有检测到的GT的数量

  • TN:不使用。

2.关于AP与PR曲线的面积

由前面定义,我们可以知道,要计算mAP必须先绘出各类别PR曲线,计算出AP。

1)积分求解

AP既然是PR曲线下的面积,那么可以通过积分来求解,即

          AP=\int_0^1 P(r) dr

2)插值求解

但通常情况下都是使用估算或者插值的方式计算:

(1)approximated average precision:

         估算计算方式

         AP=\sum_{k=1}^N P(k) \Delta r(k)

(2)Interpolated average precision

         插值计算方式

         P_{interp}(k)=max_{\hat k \ge k} P(\hat k)

         \sum_{k=1}^N P_{interp(k)} \Delta r(k)

  • k 为每一个样本点的索引,参与计算的是所有样本点

  • P_{interp(k)}取第 k 个样本点之后的样本中的最大值。

(3)插值方式进一步演变

         P_{interp}(k)=max_{\hat k \ge k} P(\hat k)

         \sum_{k=1}^K P_{interp}(k) \Delta r(k)

         这是通常意义上的 Interpolated 形式的 AP,VOC10后采用此方式。

3.VOC采取的两种插值方式

如何采样PR曲线,VOC采用过两种不同方法。

参见:The PASCAL Visual Object Classes Challenge 2012 (VOC2012) Development Kit

在VOC2010以前,只需要选取当Recall >= 0, 0.1, 0.2, ..., 1共11个点时的Precision最大值,然后AP就是这11个Precision的平均值。在VOC2010及以后,需要针对每一个不同的Recall值(包括0和1),选取其大于等于这些Recall值时的Precision最大值,然后计算PR曲线下面积作为AP值。

1)11-point interpolation(VOC07,10之前)

11-point interpolation通过平均一组11个等间距的Recall值[0,0.1,0.2,...,1]对应的Precision来绘制P-R曲线.

计算precision时采用一种插值方法(interpolate),即对于某个recall值r,precision值取所有recall>=r中的最大值(这样保证了p-r曲线是单调递减的,避免曲线出现抖动)

 2)Interpolating all points(VOC10之后)

 

不再是对召回率在[0,1]之间的均匀分布的11个点,而是对每个不同的recall值都计算一个ρinterp(r),然后求平均,r取recall>=r+1的最大precision值。

 

4.mAP计算示例(两种VOC方式比较)

一个例子有助于我们更好地理解插值平均精度的概念。 考虑下面的检测:

有7个图像,其中15个ground truth objects由绿色边界框表示,24个检测到的对象由红色边界框表示。 每个检测到的对象由字母(A,B,...,Y)标识,且具有confidence。

 

下表显示了具有相应置信度的边界框。 最后一列将检测标识为TP或FP。 在此示例中,如果IOU>=30%,则考虑TP,否则为FP。 通过查看上面的图像,我们可以粗略地判断检测是TP还是FP。

 

在一些图像中,存在多于一个与同一个ground truth重叠的检测结果(图像2,3,4,5,6和7)。 对于这些情况,选择具有最高IOU的检测框,丢弃其他框。 此规则由PASCAL VOC 2012度量标准应用:“例如,单个对象的5个检测(TP)被计为1个正确检测和4个错误检测”。

通过计算累积的TP或FP检测的precision和recall来绘制P-R曲线。 为此,首先我们需要通过置信度对检测进行排序,然后我们计算每个检测的precision和recall,如下表所示:

 

根据precision和recall值绘制P-R曲线如下图

 

如前所述,有两种不同的方法可以测量插值AP:11点插值和插值所有点。 下面我们在它们之间进行比较:

1)计算11-point interpolation

11-point interpolation AP是在一组11个recall levels(0,0.1,...,1)处的平均精度。 插值精度值是通过采用其recall大于当前recall值的最大precision获得,如下图所示:

 

通过使用11-point interpolation,我们得到

                                        AP = 26.84%

 

2)计算在所有点中执行的插值

通过插值所有点,AP可以看作P-R曲线的AUC的近似值。 目的是减少曲线中摆动的影响。 通过应用之前给出的方程,我们可以获得这里将要展示的区域。 我们还可以通过查看从最高(0.4666)到0(从右到左看图)的recall来直观地获得插值precision,并且当我们减少recall时,我们获得最高的precision值如下图所示:

 

看一下上图,我们可以将AUC划分为4个区域(A1,A2,A3和A4):

 

计算总面积,可以得到AP:

 

两种不同插值方法之间的结果略有不同:分别通过每点插值和11点插值分别为24.56%和26.84%。

5.VOC方式代码实现

Facebook开源的Detectron包含VOC数据集的mAP计算,这里贴出其核心实现,以对mAP的计算有更深入的理解。

1)读取xml文件

def parse_rec(filename):
     """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

2)计算precision和recall:

模型的输出包含bbox和对应的置信度(confidence),首先按照置信度降序排序,每添加一个样本,阈值就降低一点(真实情况下阈值降低,iou不一定降低,iounet就是对这里进行了改进)。这样就有多个阈值,每个阈值下分别计算对应的precision和recall。

# 计算每个类别对应的AP,mAP是所有类别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: 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.
     imagesetfile: Text file containing the list of images, one image per line.
     classname: Category name (duh)
     cachedir: Directory for caching the annotations
     [ovthresh]: Overlap threshold (default = 0.5)
     [use_07_metric]: Whether to use VOC07's 11 point AP computation
         (default False)
     """
     # 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
     if not os.path.isdir(cachedir):
         os.mkdir(cachedir)
     imageset = os.path.splitext(os.path.basename(imagesetfile))[0]
     cachefile = os.path.join(cachedir, imageset + '_annots.pkl')
     # read list of images
     with open(imagesetfile, 'r') as f:
         lines = f.readlines()
     imagenames = [x.strip() for x in lines]
 ​
     if not os.path.isfile(cachefile):
         # load annots
         recs = {}
         for i, imagename in enumerate(imagenames):
             recs[imagename] = parse_rec(annopath.format(imagename))
             if i % 100 == 0:
                 logger.info(
                     'Reading annotation for {:d}/{:d}'.format(
                         i + 1, len(imagenames)))
         # save
         logger.info('Saving cached annotations to {:s}'.format(cachefile))
         with open(cachefile, 'w') as f:
             cPickle.dump(recs, f)
     else:
         # load
         with open(cachefile, 'r') as f:
             recs = cPickle.load(f)
             
     # 提取所有测试图片中当前类别所对应的所有ground_truth
     # extract gt objects for this class
     class_recs = {}
     npos = 
     # 遍历所有测试图片
     for imagename in imagenames:
         # 找出所有当前类别对应的object
         R = [obj for obj in recs[imagename] if obj['name'] == classname]
         # 该图片中该类别对应的所有bbox
         bbox = np.array([x['bbox'] for x in R])
         difficult = np.array([x['difficult'] for x in R]).astype(np.bool)
         # 该图片中该类别对应的所有bbox的是否已被匹配的标志位
         det = [False] * len(R)
         # 累计所有图片中的该类别目标的总数,不算diffcult
         npos = npos + sum(~difficult)
         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]
     # 读取该目标对应的置信度
     confidence = np.array([float(x[1]) for x in splitlines])
     # 读取该目标对应的bbox
     BB = np.array([[float(z) for z in x[2:]] for x in splitlines])
     
     # 将该类别的检测结果按照置信度大小降序排列
     sorted_ind = np.argsort(-confidence)
     BB = BB[sorted_ind, :]
     image_ids = [image_ids[x] for x in sorted_ind]
     
     # 该类别检测结果的总数(所有检测出的bbox的数目)
     # go down dets and mark TPs and FPs
     nd = len(image_ids)
     # 用于标记每个检测结果是tp还是fp
     tp = np.zeros(nd)
     fp = np.zeros(nd)
     # 按置信度遍历每个检测结果
     for d in range(nd):
         # 取出该条检测结果所属图片中的所有ground truth
         R = class_recs[image_ids[d]]
         bb = BB[d, :].astype(float)
         ovmax = -np.inf
         BBGT = R['bbox'].astype(float)
         
         # 计算与该图片中所有ground truth的最大重叠度
         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:
             # 如果最大重叠度对应的ground truth为difficult就忽略
             if not R['difficult'][jmax]:
                 # 如果对应的最大重叠度的ground truth以前没被匹配过则匹配成功,即tp
                 if not R['det'][jmax]:
                     tp[d] = 1.
                     R['det'][jmax] = 1
                 # 若之前有置信度更高的检测结果匹配过这个ground truth,则此次检测结果为fp
                 else:
                     fp[d] = 1.
         # 该图片中没有对应类别的目标ground truth或者与所有ground truth重叠度都小于阈值
         else:
             fp[d] = 1.
 ​
             
     # 按置信度取不同数量检测结果时的累计fp和tp
     # np.cumsum([1, 2, 3, 4]) -> [1, 3, 6, 10]
     # compute precision recall
     fp = np.cumsum(fp)
     tp = np.cumsum(tp)
     # 召回率为占所有真实目标数量的比例,非减的,注意npos本身就排除了difficult,因此npos=tp+fn
     rec = tp / float(npos)
     # 精度为取的所有检测结果中tp的比例
     # 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)
     # 计算recall-precise曲线下面积(严格来说并不是面积)
     ap = voc_ap(rec, prec, use_07_metric)
 ​
     return rec, prec, ap

这里最终得到一系列的precision和recall值,并且这些值是按照置信度降低排列统计的,可以认为是取不同的置信度阈值(或者rank值)得到的。

3)计算AP:

def voc_ap(rec, prec, use_07_metric=False):
     """Compute VOC AP given precision and recall. If use_07_metric is true, uses
     the VOC 07 11-point method (default:False).
     """
     
     # VOC2010以前按recall等间隔取11个不同点处的精度值做平均(0., 0.1, 0.2, …, 0.9, 1.0)
     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:
                 # 取recall大于等于阈值的最大precision,保证precision非减
                 p = np.max(prec[rec >= t])
             ap = ap + p / 11.
             
     # VOC2010以后取所有不同的recall对应的点处的精度值做平均
     else:
         # correct AP calculation
         # first append sentinel values at the end
         mrec = np.concatenate(([0.], rec, [1.]))
         mpre = np.concatenate(([0.], prec, [0.]))
         
         # 计算包络线,从后往前取最大保证precise非减
         # compute the precision envelope
         for i in range(mpre.size - 1, 0, -1):
             mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
 ​
         # 找出所有检测结果中recall不同的点
         # 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
         # 用recall的间隔对精度作加权平均
         ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
     return ap
计算各个类别的AP值后,取平均值就可以得到最终的mAP值了。但是对于COCO数据集相对比较复杂,不过其提供了计算的API,感兴趣可以看一下cocodataset/cocoapi。

6.PASCAL数据集mAP计算方式

PASCAL VOC最终的检测结构是如下这种格式的:

比如comp3_det_test_car.txt: 

000004 0.702732 89 112 516 466
000006 0.870849 373 168 488 229
000006 0.852346 407 157 500 213
000006 0.914587 2 161 55 221
000008 0.532489 175 184 232 201

每一行依次为 :

 <image identifier> <confidence> <left> <top> <right> <bottom>

每一行都是一个bounding box,后面四个数定义了检测出的bounding box的左上角点和右下角点的坐标。

在计算mAP时,如果按照二分类问题理解,那么每一行都应该对应一个标签,这个标签可以通过ground truth计算出来。

但是如果严格按照 ground truth 的坐标来判断这个bounding box是否正确,那么这个标准就太严格了,因为这是属于像素级别的检测,所以PASCAL中规定当一个bounding box与ground truth的 IOU>0.5 时就认为这个框是正样本,标记为1;否则标记为0。这样一来每个bounding box都有个得分,也有一个标签,这时你可以认为前面的文件是这样的,后面多了一个标签项

000004 0.702732 89 112 516 466 1
000006 0.870849 373 168 488 229 0
000006 0.852346 407 157 500 213 1
000006 0.914587 2 161 55 221 0
000008 0.532489 175 184 232 201 1

进而你可以认为是这样的,后面的标签实际上是通过坐标计算出来的

000004 0.702732  1
000006 0.870849  0
000006 0.852346  1
000006 0.914587  0
000008 0.532489  1

这样一来就可以根据前面博客中的二分类方法计算AP了。但这是某一个类别的,将所有类别的都计算出来,再做平均即可得到mAP.

7.COCO数据集AP计算方式

COCO数据集里的评估标准比PASCAL 严格许多

COCO检测出的结果是json文件格式,比如下面的:

[
       {
             "image_id": 139,
             "category_id": 1,
             "bbox": [
                 431.23001,
                 164.85001,
                 42.580002,
                 124.79
             ],
             "score": 0.16355941
       }, 
     ……
     ……
 ]

我们还是按照前面的形式来便于理解: 

000004 0.702732 89 112 516 466
000006 0.870849 373 168 488 229
000006 0.852346 407 157 500 213
000006 0.914587 2 161 55 221
000008 0.532489 175 184 232 201

前面提到可以使用IOU来计算出一个标签,PASCAL用的是 IOU>0.5即认为是正样本,但是COCO要求IOU阈值在[0.5, 0.95]区间内每隔0.05取一次,这样就可以计算出10个类似于PASCAL的mAP,然后这10个还要再做平均,即为最后的AP,COCO中并不将AP与mAP做区分,许多论文中的写法是 AP@[0.5:0.95]。而COCO中的 AP@0.5 与PASCAL 中的mAP是一样的。

8.参考资料

知乎回答

Object-Detection-Metrics

目标检测mAP计算方式

目标检测评价标准-AP mAP

目标检测模型的评估指标mAP详解(附代码)

How to calculate mAP for detection task for the PASCAL VOC Challenge

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值