目标检测算法之常见评价指标的详细计算方法及代码解析

亦凉 2023-06-28 04:52 27阅读 0赞

前言

之前简单介绍过目标检测算法的一些评价标准,地址为目标检测算法之评价标准和常见数据集盘点。然而这篇文章仅仅只是从概念性的角度来阐述了常见的评价标准如Acc,Precision,Recall,AP等。并没有从源码的角度来分析具体的计算过程,这一篇推文的目的就是结合代码再次详细的解释目标检测算法中的常见评价标准如Precision,Recall,AP,mAP的具体计算过程。

评价指标

由于在上面那篇推文中已经详细解释过了,所以这里就只是简单的再回顾一下,详细的请移步那篇推文看看。为了方便理解,还是先说一下TP,TN,FP,FN的含义。

一个经典例子是存在一个测试集合,测试集合只有大雁和飞机两种图片组成,假设你的分类系统最终的目的是:能取出测试集中所有飞机的图片,而不是大雁的图片。然后就可以定义:

  • True positives: 简称为TP,即正样本被正确识别为正样本,飞机的图片被正确的识别成了飞机。
  • True negatives: 简称为TN,即负样本被正确识别为负样本,大雁的图片没有被识别出来,系统正确地认为它们是大雁。
  • False Positives: 简称为FP,即负样本被错误识别为正样本,大雁的图片被错误地识别成了飞机。
  • False negatives: 简称为FN,即正样本被错误识别为负样本,飞机的图片没有被识别出来,系统错误地认为它们是大雁。

接下来我们就开始定义一些评价标准:

  • 准确率(Acc):准确率(Acc)的计算公式为 A c c = T P + T N N Acc=\frac{TP+TN}{N} Acc=NTP+TN,即预测正确的样本比例, N N N代表测试的样本数。在检测任务中没有预测正确的负样本的概念,所以Acc自然用不到了。
  • 查准率(Precision):查准率是针对某一个具体类别而言的,公式为: P r e c i s i o n = T P T P + F P = T P N Precision=\frac{TP}{TP+FP}=\frac{TP}{N} Precision=TP+FPTP=NTP,其中N代表所有检测到的某个具体类的目标框个数。
  • 召回率(Recall):召回率仍然是针对某一个具体类别而言的,公式为: R e c a l l = T P T P + F N Recall=\frac{TP}{TP+FN} Recall=TP+FNTP,即预测正确的目标框和所有Ground Truth框的比值。
  • F1 Score:定位Wie查准率和召回率的调和平均,公式如下: F 1 = 2 × P r e c i s i o n ∗ R e c a l l P r e c i s i o n + R e c a l l = 2 T P 2 T P + F N + F P F_1=2\times \frac{Precision * Recall}{Precision + Recall}=\frac{2TP}{2TP+FN+FP} F1=2×Precision+RecallPrecision∗Recall=2TP+FN+FP2TP。
  • IOU:先为计算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曲线怎么来的?可以在这篇论文找到答案,截图如下:

在这里插入图片描述
我来解释一下,要得到Precision-Recall曲线(以下简称PR)曲线,首先要对检测模型的预测结果按照目标置信度降序排列。然后给定一个rank值,Recall和Precision仅在置信度高于该rank值的预测结果中计算,改变rank值会相应的改变Recall值和Precision值。这里选择了11个不同的rank值,也就得到了11组Precision和Recall值,然后AP值即定义为在这11个Recall下Precision值的平均值,其可以表征整个PR曲线下方的面积。即:

在这里插入图片描述

还有另外一种插值的计算方法,即对于某个Recall值r,Precision取所有Recall值大于r中的最大值,这样保证了PR曲线是单调递减的,避免曲线出现摇摆。另外需要注意的一点是在2010年后计算AP值时是取了所有的数据点,而不仅仅只是11个Recall值。我们在计算出AP之后,对所有类别求平均之后就是mAP值了,也是当前目标检测用的最多的评判标准。

  • AP50,AP60,AP70等等代表什么意思?代表IOU阈值分别取0.5,0.6,0.7等对应的AP值。

代码解析

下面解析一下Faster-RCNN中对VOC数据集计算每个类别AP值的代码,mAP就是所有类的AP值平均值。代码来自py-faster-rcnn项目,链接见附录。代码解析如下:

  1. # --------------------------------------------------------
  2. # Fast/er R-CNN
  3. # Licensed under The MIT License [see LICENSE for details]
  4. # Written by Bharath Hariharan
  5. # --------------------------------------------------------
  6. import xml.etree.ElementTree as ET #读取xml文件
  7. import os
  8. import cPickle #序列化存储模块
  9. import numpy as np
  10. def parse_rec(filename):
  11. """ Parse a PASCAL VOC xml file """
  12. tree = ET.parse(filename)
  13. objects = []
  14. # 解析xml文件,将GT框信息放入一个列表
  15. for obj in tree.findall('object'):
  16. obj_struct = {}
  17. obj_struct['name'] = obj.find('name').text
  18. obj_struct['pose'] = obj.find('pose').text
  19. obj_struct['truncated'] = int(obj.find('truncated').text)
  20. obj_struct['difficult'] = int(obj.find('difficult').text)
  21. bbox = obj.find('bndbox')
  22. obj_struct['bbox'] = [int(bbox.find('xmin').text),
  23. int(bbox.find('ymin').text),
  24. int(bbox.find('xmax').text),
  25. int(bbox.find('ymax').text)]
  26. objects.append(obj_struct)
  27. return objects
  28. # 单个计算AP的函数,输入参数为精确率和召回率,原理见上面
  29. def voc_ap(rec, prec, use_07_metric=False):
  30. """ ap = voc_ap(rec, prec, [use_07_metric])
  31. Compute VOC AP given precision and recall.
  32. If use_07_metric is true, uses the
  33. VOC 07 11 point method (default:False).
  34. """
  35. # 如果使用2017年的计算AP的方式(插值的方式)
  36. if use_07_metric:
  37. # 11 point metric
  38. ap = 0.
  39. for t in np.arange(0., 1.1, 0.1):
  40. if np.sum(rec >= t) == 0:
  41. p = 0
  42. else:
  43. p = np.max(prec[rec >= t])
  44. ap = ap + p / 11.
  45. else:
  46. # 使用2010年后的计算AP值的方式
  47. # 这里是新增一个(0,0),方便计算
  48. mrec = np.concatenate(([0.], rec, [1.]))
  49. mpre = np.concatenate(([0.], prec, [0.]))
  50. # compute the precision envelope
  51. for i in range(mpre.size - 1, 0, -1):
  52. mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
  53. # to calculate area under PR curve, look for points
  54. # where X axis (recall) changes value
  55. i = np.where(mrec[1:] != mrec[:-1])[0]
  56. # and sum (\Delta recall) * prec
  57. ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
  58. return ap
  59. # 主函数
  60. def voc_eval(detpath,
  61. annopath,
  62. imagesetfile,
  63. classname,
  64. cachedir,
  65. ovthresh=0.5,
  66. use_07_metric=False):
  67. """rec, prec, ap = voc_eval(detpath,
  68. annopath,
  69. imagesetfile,
  70. classname,
  71. [ovthresh],
  72. [use_07_metric])
  73. Top level function that does the PASCAL VOC evaluation.
  74. detpath: 产生的txt文件,里面是一张图片的各个检测框结果。
  75. annopath: xml 文件与对应的图像相呼应。
  76. imagesetfile: 一个txt文件,里面是每个图片的地址,每行一个地址。
  77. classname: 种类的名字,即类别。
  78. cachedir: 缓存标注的目录。
  79. [ovthresh]: IOU阈值,默认为0.5,即mAP50。
  80. [use_07_metric]: 是否使用2007的计算AP的方法,默认为Fasle
  81. """
  82. # assumes detections are in detpath.format(classname)
  83. # assumes annotations are in annopath.format(imagename)
  84. # assumes imagesetfile is a text file with each line an image name
  85. # cachedir caches the annotations in a pickle file
  86. # 首先加载Ground Truth标注信息。
  87. if not os.path.isdir(cachedir):
  88. os.mkdir(cachedir)
  89. # 即将新建文件的路径
  90. cachefile = os.path.join(cachedir, 'annots.pkl')
  91. # 读取文本里的所有图片路径
  92. with open(imagesetfile, 'r') as f:
  93. lines = f.readlines()
  94. # 获取文件名,strip用来去除头尾字符、空白符(包括\n、\r、\t、' ',即:换行、回车、制表符、空格)
  95. imagenames = [x.strip() for x in lines]
  96. #如果cachefile文件不存在,则写入
  97. if not os.path.isfile(cachefile):
  98. # load annots
  99. recs = {}
  100. for i, imagename in enumerate(imagenames):
  101. #annopath.format(imagename): label的xml文件所在的路径
  102. recs[imagename] = parse_rec(annopath.format(imagename))
  103. if i % 100 == 0:
  104. print 'Reading annotation for {:d}/{:d}'.format(
  105. i + 1, len(imagenames))
  106. # save
  107. print 'Saving cached annotations to {:s}'.format(cachefile)
  108. with open(cachefile, 'w') as f:
  109. #写入cPickle文件里面。写入的是一个字典,左侧为xml文件名,右侧为文件里面个各个参数。
  110. cPickle.dump(recs, f)
  111. else:
  112. # load
  113. with open(cachefile, 'r') as f:
  114. recs = cPickle.load(f)
  115. # 对每张图片的xml获取函数指定类的bbox等
  116. class_recs = {}# 保存的是 Ground Truth的数据
  117. npos = 0
  118. for imagename in imagenames:
  119. # 获取Ground Truth每个文件中某种类别的物体
  120. R = [obj for obj in recs[imagename] if obj['name'] == classname]
  121. bbox = np.array([x['bbox'] for x in R])
  122. # different基本都为0/False
  123. difficult = np.array([x['difficult'] for x in R]).astype(np.bool)
  124. det = [False] * len(R)
  125. npos = npos + sum(~difficult) #自增,~difficult取反,统计样本个数
  126. # # 记录Ground Truth的内容
  127. class_recs[imagename] = {'bbox': bbox,
  128. 'difficult': difficult,
  129. 'det': det}
  130. # read dets 读取某类别预测输出
  131. detfile = detpath.format(classname)
  132. with open(detfile, 'r') as f:
  133. lines = f.readlines()
  134. splitlines = [x.strip().split(' ') for x in lines]
  135. image_ids = [x[0] for x in splitlines] # 图片ID
  136. confidence = np.array([float(x[1]) for x in splitlines]) # IOU值
  137. BB = np.array([[float(z) for z in x[2:]] for x in splitlines]) # bounding box数值
  138. # 对confidence的index根据值大小进行降序排列。
  139. sorted_ind = np.argsort(-confidence)
  140. sorted_scores = np.sort(-confidence)
  141. #重排bbox,由大概率到小概率。
  142. BB = BB[sorted_ind, :]
  143. # 图片重排,由大概率到小概率。
  144. image_ids = [image_ids[x] for x in sorted_ind]
  145. # go down dets and mark TPs and FPs
  146. nd = len(image_ids)
  147. tp = np.zeros(nd)
  148. fp = np.zeros(nd)
  149. for d in range(nd):
  150. R = class_recs[image_ids[d]]
  151. bb = BB[d, :].astype(float)
  152. ovmax = -np.inf
  153. BBGT = R['bbox'].astype(float)
  154. if BBGT.size > 0:
  155. # compute overlaps
  156. # intersection
  157. ixmin = np.maximum(BBGT[:, 0], bb[0])
  158. iymin = np.maximum(BBGT[:, 1], bb[1])
  159. ixmax = np.minimum(BBGT[:, 2], bb[2])
  160. iymax = np.minimum(BBGT[:, 3], bb[3])
  161. iw = np.maximum(ixmax - ixmin + 1., 0.)
  162. ih = np.maximum(iymax - iymin + 1., 0.)
  163. inters = iw * ih
  164. # union
  165. uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) +
  166. (BBGT[:, 2] - BBGT[:, 0] + 1.) *
  167. (BBGT[:, 3] - BBGT[:, 1] + 1.) - inters)
  168. overlaps = inters / uni
  169. ovmax = np.max(overlaps)
  170. jmax = np.argmax(overlaps)
  171. if ovmax > ovthresh:
  172. if not R['difficult'][jmax]:
  173. if not R['det'][jmax]:
  174. tp[d] = 1.
  175. R['det'][jmax] = 1
  176. else:
  177. fp[d] = 1.
  178. else:
  179. fp[d] = 1.
  180. # compute precision recall
  181. fp = np.cumsum(fp)
  182. tp = np.cumsum(tp)
  183. rec = tp / float(npos)
  184. # avoid divide by zero in case the first detection matches a difficult
  185. # ground truth
  186. prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
  187. ap = voc_ap(rec, prec, use_07_metric)
  188. return rec, prec, ap

这个脚本可以直接调用来计算mAP值,可以看一下附录中的最后一个链接。

附录

  • http://host.robots.ox.ac.uk/pascal/VOC/pubs/everingham15.pdf
  • http://homepages.inf.ed.ac.uk/ckiw/postscript/ijcv\_voc09.pdf
  • 代码链接:https://github.com/rbgirshick/py-faster-rcnn/blob/master/lib/datasets/voc\_eval.py
  • 在Darknet中调用上面的脚本来计算mAP值:https://blog.csdn.net/amusi1994/article/details/81564504

欢迎关注我的微信公众号GiantPandaCV,期待和你一起交流机器学习,深度学习,图像算法,优化技术,比赛及日常生活等。

图片.png

发表评论

表情:
评论列表 (有 0 条评论,27人围观)

还没有评论,来说两句吧...

相关阅读