详解目标检测模型的评价指标及代码实现

您所在的位置:网站首页 华为olt数据详解 详解目标检测模型的评价指标及代码实现

详解目标检测模型的评价指标及代码实现

2023-03-26 06:39| 来源: 网络整理| 查看: 265

摘要:为了评价模型的泛化能力,即判断模型的好坏,我们需要用某个指标来衡量,有了评价指标,就可以对比不同模型的优劣,并通过这个指标来进一步调参优化模型。

本文分享自华为云社区《​​目标检测模型的评价指标详解及代码实现​​》,作者:嵌入式视觉。

前言

为了了解模型的泛化能力,即判断模型的好坏,我们需要用某个指标来衡量,有了评价指标,就可以对比不同模型的优劣,并通过这个指标来进一步调参优化模型。对于分类和回归两类监督模型,分别有各自的评判标准。

不同的问题和不同的数据集都会有不同的模型评价指标,比如分类问题,数据集类别平衡的情况下可以使用准确率作为评价指标,但是现实中的数据集几乎都是类别不平衡的,所以一般都是采用 AP 作为分类的评价指标,分别计算每个类别的 AP,再计算mAP。

一,精确率、召回率与F11.1,准确率

准确率(精度) – Accuracy,预测正确的结果占总样本的百分比,定义如下:

准确率=(TP+TN)/(TP+TN+FP+FN)

错误率和精度虽然常用,但是并不能满足所有任务需求。以西瓜问题为例,假设瓜农拉来一车西瓜,我们用训练好的模型对西瓜进行判别,现如精度只能衡量有多少比例的西瓜被我们判断类别正确(两类:好瓜、坏瓜)。但是若我们更加关心的是“挑出的西瓜中有多少比例是好瓜”,或者”所有好瓜中有多少比例被挑出来“,那么精度和错误率这个指标显然是不够用的。

虽然准确率可以判断总的正确率,但是在样本不平衡的情况下,并不能作为很好的指标来衡量结果。举个简单的例子,比如在一个总样本中,正样本占 90%,负样本占 10%,样本是严重不平衡的。对于这种情况,我们只需要将全部样本预测为正样本即可得到 90% 的高准确率,但实际上我们并没有很用心的分类,只是随便无脑一分而已。这就说明了:由于样本不平衡的问题,导致了得到的高准确率结果含有很大的水分。即如果样本不平衡,准确率就会失效。

1.2,精确率、召回率

精确率(查准率)P、召回率(查全率)R 的计算涉及到混淆矩阵的定义,混淆矩阵表格如下:

详解目标检测模型的评价指标及代码实现_评价指标

查准率与查全率计算公式:

查准率(精确率)P=TP/(TP+FP)P=TP/(TP+FP)查全率(召回率)R=TP/(TP+FN)R=TP/(TP+FN)

精准率和准确率看上去有些类似,但是完全不同的两个概念。精准率代表对正样本结果中的预测准确程度,而准确率则代表整体的预测准确程度,既包括正样本,也包括负样本。

精确率描述了模型有多准,即在预测为正例的结果中,有多少是真正例;召回率则描述了模型有多全,即在为真的样本中,有多少被我们的模型预测为正例。精确率和召回率的区别在于分母不同,一个分母是预测为正的样本数,另一个是原来样本中所有的正样本数。

1.3,F1 分数

如果想要找到 P 和 R 二者之间的一个平衡点,我们就需要一个新的指标:F1 分数。F1 分数同时考虑了查准率和查全率,让二者同时达到最高,取一个平衡。F1 计算公式如下:

这里的 F1 计算是针对二分类模型,多分类任务的 F1 的计算请看下面。

详解目标检测模型的评价指标及代码实现_监督模型_02

F1 度量的一般形式:Fβ,能让我们表达出对查准率/查全率的偏见,Fβ 计算公式如下:

详解目标检测模型的评价指标及代码实现_监督模型_03

其中β>1 对查全率有更大影响,β= 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

2、给定目标检测结果文件和测试集标签文件 xml 等计算 AP:

def parse_rec(filename): """ Parse a PASCAL VOC xml file Return : list, element is dict. """ 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 objectsdef 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 result file detpath.format(classname) should produce the detection results file. annopath: Path to annotations file 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) cachefile = os.path.join(cachedir, '%s_annots.pkl' % imagesetfile) # 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 annotations recs = {} for i, imagename in enumerate(imagenames): recs[imagename] = parse_rec(annopath.format(imagename)) 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, 'wb') as f: pickle.dump(recs, f) else: # load with open(cachefile, 'rb') as f: try: recs = pickle.load(f) except: recs = pickle.load(f, encoding='bytes') # extract gt objects for this class class_recs = {} npos = 0 for imagename in imagenames: R = [obj for obj in recs[imagename] if obj['name'] == classname] bbox = np.array([x['bbox'] for x in R]) difficult = np.array([x['difficult'] for x in R]).astype(np.bool) det = [False] * len(R) 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]) BB = np.array([[float(z) for z in x[2:]] for x in splitlines]) nd = len(image_ids) tp = np.zeros(nd) fp = np.zeros(nd) if BB.shape[0] > 0: # sort by confidence sorted_ind = np.argsort(-confidence) sorted_scores = np.sort(-confidence) BB = BB[sorted_ind, :] image_ids = [image_ids[x] for x in sorted_ind] # go down dets and mark TPs and FPs for d in range(nd): R = class_recs[image_ids[d]] bb = BB[d, :].astype(float) ovmax = -np.inf BBGT = R['bbox'].astype(float) 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: if not R['difficult'][jmax]: if not R['det'][jmax]: tp[d] = 1. R['det'][jmax] = 1 else: fp[d] = 1. else: fp[d] = 1. # compute precision recall fp = np.cumsum(fp) tp = np.cumsum(tp) rec = tp / float(npos) # 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) ap = voc_ap(rec, prec, use_07_metric) return rec, prec, ap2.4,mAP 计算方法

因为 mAP 值的计算是对数据集中所有类别的 AP 值求平均,所以我们要计算 mAP,首先得知道某一类别的 AP 值怎么求。不同数据集的某类别的 AP 计算方法大同小异,主要分为三种:

(1)在 VOC2007,只需要选取当 Recall>=0,0.1,0.2,...,1Recall>=0,0.1,0.2,...,1 共 11 个点时的 Precision 最大值,然后 APAP 就是这 11 个 Precision 的平均值,mAPmAP 就是所有类别 APAP 值的平均。VOC 数据集中计算 APAP 的代码(用的是插值计算方法,代码出自​​py-faster-rcnn仓库​​)

(2)在 VOC2010 及以后,需要针对每一个不同的 Recall 值(包括 0 和 1),选取其大于等于这些 Recall 值时的 Precision 最大值,然后计算 PR 曲线下面积作为 AP 值,mAPmAP 就是所有类别 AP 值的平均。

(3)COCO 数据集,设定多个 IOU 阈值(0.5-0.95, 0.05 为步长),在每一个 IOU 阈值下都有某一类别的 AP 值,然后求不同 IOU 阈值下的 AP 平均,就是所求的最终的某类别的 AP 值。

三,目标检测度量标准汇总

详解目标检测模型的评价指标及代码实现_监督模型_13

详解目标检测模型的评价指标及代码实现_混淆矩阵_14

四,参考资料目标检测评价标准-AP mAP目标检测的性能评价指标Soft-NMS​​Recent Advances in Deep Learning for Object Detection​​​​A Simple and Fast Implementation of Faster R-CNN​​分类模型评估指标——准确率、精准率、召回率、F1、ROC曲线、AUC曲线一文让你彻底理解准确率,精准率,召回率,真正率,假正率,ROC/AUC

​​点击关注,第一时间了解华为云新鲜技术~​​



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3