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 2010use_07_metric = True if int(self._year) < 2010 else Falseprint('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__':continuefilename = 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 npdef 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').textobj_struct['pose'] = obj.find('pose').textobj_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 objectsdef 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 theVOC 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 metricap = 0.for t in np.arange(0., 1.1, 0.1):if np.sum(rec >= t) == 0:p = 0else:p = np.max(prec[rec >= t])ap = ap + p / 11.else:# correct AP calculation# first append sentinel values at the endmrec = np.concatenate(([0.], rec, [1.]))mpre = np.concatenate(([0.], prec, [0.]))# compute the precision envelopefor 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 valuei = np.where(mrec[1:] != mrec[:-1])[0]# and sum (\Delta recall) * precap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])return apdef voc_eval(detpath,  ######主函数,计算当前类别的recall和precisionannopath,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 detectionsdetpath.format(classname) should produce the detection results file.annopath: Path to annotationsannopath.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 imageswith open(imagesetfile, 'r') as f:lines = f.readlines() #读取所有待检测图片名。imagenames = [x.strip() for x in lines] #待检测图像文件名字存于数组imagenames,长度1000。if not os.path.isfile(cachefile): #如果只读文件不存在,则只好从原始数据集中重新加载数据# load annotsrecs = {}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)) #进度条。# saveprint 'Saving cached annotations to {:s}'.format(cachefile)with open(cachefile, 'w') as f:cPickle.dump(recs, f) #recs字典c保存到只读文件。else:# loadwith 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]) #抽取bboxdifficult = 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长度20000image_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,不是1000tp = np.zeros(nd) # true positive,长度20000fp = np.zeros(nd) # false positive,长度20000for d in range(nd): #遍历所有检测结果,因为已经排序,所以这里是从置信度最高到最低遍历R = class_recs[image_ids[d]] #当前检测结果所在图像的所有同类别gtbb = BB[d, :].astype(float) #当前检测结果bbox坐标ovmax = -np.infBBGT = R['bbox'].astype(float) #当前检测结果所在图像的所有同类别gt的bbox坐标if BBGT.size > 0: # compute overlaps 计算当前检测结果,与该检测结果所在图像的标注重合率,一对多用到python的broadcast机制# intersectionixmin = 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# unionuni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) +(BBGT[:, 2] - BBGT[:, 0] + 1.) *(BBGT[:, 3] - BBGT[:, 1] + 1.) - inters)overlaps = inters / uniovmax = np.max(overlaps)#最大重合率jmax = np.argmax(overlaps)#最大重合率对应的gtif ovmax > ovthresh:#如果当前检测结果与真实标注最大重合率满足阈值if not R['difficult'][jmax]:if not R['det'][jmax]:tp[d] = 1. #正检数目+1R['det'][jmax] = 1 #该gt被置为已检测到,下一次若还有另一个检测结果与之重合率满足阈值,则不能认为多检测到一个目标else: #相反,认为检测到一个虚警fp[d] = 1.else: #不满足阈值,肯定是虚警fp[d] = 1.# compute precision recallfp = 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到0prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)ap = voc_ap(rec, prec, use_07_metric)return rec, prec, ap

Mean Average Precision(MAP):平均精度均值相关推荐

  1. 深度学习目标检测中计算目标的AP(average precision)平均精度、有什么用?

    AP衡量的是学出来的模型在每个类别上的好坏,mAP衡量的是学出的模型在所有类别上的好坏,得到AP后mAP的计算就变得很简单了,就是取所有AP的平均值. 参考文章:深度学习-目标检测评估指标P-R曲线. ...

  2. 平均精度均值(Mean Average Precision, mAP)

    目录 一.Mean Average Precision -- mAP (一)什么是 mAP ? (二)mAP 是怎么计算的? 2.准确率.召回率.精确度 (1)准确率 -- precision &am ...

  3. 【深度学习】什么是目标检测中的平均精度均值(mAP)?

    计算机视觉界已经集中在度量 mAP 上,来比较目标检测系统的性能.在这篇文章中,我们将深入了解平均精度均值 (mAP) 是如何计算的,以及为什么 mAP 已成为目标检测的首选指标. 目标检测的快速概述 ...

  4. 什么是目标检测中的平均精度均值(mAP)?

    点击上方"小白学视觉",选择加"星标"或"置顶" 重磅干货,第一时间送达 计算机视觉界已经集中在度量 mAP 上,来比较目标检测系统的性能. ...

  5. yolo-v2 v3实现笔记 mAP:mean average precision 平均精度均值

    mAP计算参考这里:目标检测的评估指标mAP的那些事儿 相关概念:机器学习中 True Positives(真正例TP).False Positives(假正例FP).True Negatives(真 ...

  6. MAP-Mean Average Precision 平均精度均值

    在分类任务中,不知道是不是多标签分类,看完本文就知道了. [MAP常用于检测识别,是先(检测)分割,然后(分类)识别,是连续的过程] 除了常见的评价指标外,还有一个能装逼的指标,因为知道的人少了一些. ...

  7. map(平均平均精度_客户的平均平均精度

    map(平均平均精度 Disclaimer: this was created for my clients because it's rather challenging to explain su ...

  8. MAP(Mean Average Precision)

    from: http://blog.sina.com.cn/s/blog_662234020100pozd.html MAP(Mean Average Precision) MAP(Mean Aver ...

  9. MAP 推荐系统 Mean Average Precision

    MAP 推荐系统 Mean Average Precision 简介 拓展 简介 因被审稿人要求添加MAP指标,在学习时发现网上资料对于在推荐系统中使用MAP指标的介绍不甚清晰,故写此文,总结分享,若 ...

最新文章

  1. hi3559 h264
  2. 【图像超分辨率论文】BasicVSR++: Improving Video Super-Resolution with Enhanced Propagation and Alignment
  3. 该如何弥补 GitHub 功能缺陷?
  4. Java JDK 10:下一代 Java 有哪些新特性?
  5. C# 连接 Exchange 发送邮件
  6. java为什么安装怎么慢_Java JDK下载为什么慢? 国内下载站来解决
  7. [渝粤教育] 中国地质大学 微积分(二) 复习题 (2)
  8. java发牌_Java实现洗牌发牌的方法
  9. J2EE是技术还是平台还是框架? 什么是J2EE
  10. 3 a 5的c语言表达式,C语言中,赋值表达式:(a=3*5)=4*3,为什么整个表达式的值为1,表达式x=(a=3,6*a)和表达式x=a=3,6*a分别是...
  11. Cilium 官方文档翻译(7) IPAM Kubernetes Host模式
  12. 包含tsx的react项目创建
  13. Python 列表转为字典
  14. 永恒之蓝实验 MS17-010
  15. 懒惰、急躁和傲慢(Laziness, Impatience and hubris)
  16. vue-video-player,springboot实现视频分段下载播放
  17. Java servlet生命周期
  18. 视频翻译成文字的软件有哪些?推荐几个软件给你
  19. 解码百度Q4财报,智能云、自动驾驶非广告业务表现亮眼
  20. java(服务器端)调用支付宝和微信支付功能

热门文章

  1. 用友携YonSuite亮相云栖大会,全方位生态合作再提速
  2. 小菜鸟之oracle数据字典
  3. 常见的考勤管理系统有哪些功能?
  4. Flutter 必备开源项目
  5. 云呐:2022学校固定资产盘点,学校RFID固定资产盘点计划方案
  6. python程序员可以从哪些平台接单赚钱?看完我给你介绍的这几个平台,没学过python的你也能边学习边赚钱
  7. 【视频】什么是Bootstrap自抽样及应用R语言线性回归预测置信区间实例|数据分享
  8. C++中四种类型转换运算符的使用方法
  9. 一看就觉得特别好的21条感悟
  10. mysql 星座_mysql 查询年龄段,星座以及最近7天生日的sql