mAP计算

1. TP、TN、FP、FN解释说明

  • 行表示预测的label值,列表示真实label值
  • TP:True Positive, 被判定为正样本,事实上也是正样本。
  • FP:False Positive,被判定为正样本,但事实上是负样本。
  • TN:True Negative, 被判定为负样本,事实上也是负样本。
  • FN:False Negative,被判定为负样本,但事实上是正样本。

“狼来了”的故事模型

langlaile

2. precision 和 recall 的计算

  • Accuracy:表示预测结果的精确度,预测正确的样本数除以总样本数。
  • precision: 准确率,又称为查准率,表示预测结果中,预测为正样本的样本中,正确预测为正样本的概率;
  • recall: 召回率,又称为查全率,表示在原始样本的正样本中,最后被正确预测为正样本的概率;

计算公式如下图:

3. 精确率和召回率:一场拔河比赛,鱼与熊掌的关系

要全面评估模型的有效性,必须同时检查精确率和召回率。遗憾的是,精确率和召回率往往是此消彼长的情况。也就是说,提高精确率通常会降低召回率值,

在多分类中,最后经过一个softmax层,输出值是预测结果的概率,把模型预测为某个对象的概率从高到低排序,并且和真实标签对应。

这时我们会设置某个阈值,大于这个阈值的分为正样本,反之为负样本。随着选取的阈值不同,得到的指标是不一样的。这时我们可以画P-R曲线。

4. P-R曲线、平均精度(Average-Precision,AP)

P-R曲线:选取不同阈值时对应的精度和召回画出来

P-R图直观地显示出学习器在样本总体上的查全率、查准率.总体趋势,精度越高,召回越低,进行比较

  • 若一个学习器的P-R曲线被另一个学习器的曲线完全“包住”,则可断言后者的性能优于前者,如图中学习器A的性能优于学习器C;
  • 如果两个学习器的P-R曲线发生了交叉,如图中的A与B,则难以一般性地断言两者孰优孰劣? 只能在具体的查准率或查全率条件下进行比较.

然而, 在很多情形下,人们往往仍希望把学习器A与B比出个高低.这时一个比较合理的判据是比较P-R曲线下面积的大小, 它在一定程度上表征了学习器在查准率和查全率上取得相对“双高”的比例但这个值不太容易估算,因此,人们设计了一些综合考虑查准率、查全率的性能度量

“平衡点”(Break Event Point,简称BEP )就是这样一个度量,它是“查准率=查全率”时的取值, 如图中学习器C的BEP 是0.64, 而基于BEP的比较,可认为学习器A 优于B.

但BEP 还是过于简化了些,更常用的是Fl 度量

5. 平均精度(Average-Precision,AP):

P-R曲线围起来的面积,通常来说一个越好的分类器,AP值越高。
AP衡量的是学出来的模型在每个类别上的好坏,
mAP衡量的是学出的模型在所有类别上的好坏,得到AP后mAP的计算就变得很简单了,就是取所有AP的平均值。

6. AP的计算

此处参考的是PASCAL VOC CHALLENGE的计算方法。首先设定一组阈值,[0, 0.1, 0.2, …, 1]。然后对于recall大于每一个阈值(比如recall>0.3),我们都会得到一个对应的最大precision。这样,我们就计算出了11个precision。AP即为这11个precision的平均值。这种方法英文叫做11-point interpolated average precision。​
当然PASCAL VOC CHALLENGE自2010年后就换了另一种计算方法。新的计算方法假设这N个样本中有M个正例,那么我们会得到M个recall值(1/M, 2/M, …, M/M),对于每个recall值r,我们可以计算出对应(r’ > r)的最大precision,然后对这M个precision值取平均即得到最后的AP值。计算方法如下:​

相应的Precision-Recall曲线(这条曲线是单调递减的)如下:

7. 计算代码

两种方式的计算:

def voc_eval(tag,
             det_txt_path,
             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)
    cachefile = os.path.join(cachedir, tag + '_annots.pkl')
    ## read list of images
    ## imagesetfile 需要测试的图片集合 test.txt
    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):
            ## parse_rec 返回每张图片的全部物品数量
            recs[imagename] = parse_rec(os.path.join(annopath, imagename + '.xml'))
            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:
            recs = pickle.load(f)

    ## extract gt objects for this class
    ## class_recs 每个图片中真实物品数, 里面的量bbox,difficult都是列表,
    ## 提取所有测试图片中当前类别所对应的所有ground_truth
    class_recs = {}
    npos = 0
    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 为 bool 类型数据
        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 = det_txt_path
    print('detect file path :', detfile)
    ## 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])

    ## sort by confidence
    ## argsort函数返回的是数组值从小到大的索引值
    ## 将该类别的检测结果按照置信度大小降序排列
    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
    ## image_ids 检测出来的数量
    ## 该类别检测结果的总数(所有检测出的bbox的数目)
    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)  ## BB是检测出来的 物品坐标.
        ovmax = -np.inf
        BBGT = R['bbox'].astype(float)  ## BBGT 图片真实位置坐标, 是列表
        ## 计算与该图片中所有ground truth的最大重叠度
        if BBGT.size > 0:
            ## compute overlaps
            ## intersection  np.maximum X 与 Y 逐位比较取其大者,得到交集的两个坐标.
            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)  ## argmax返回的是最大数的索引
        ## 如果最大的重叠度大于一定的阈值
        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
                else:
                    fp[d] = 1.
        ## 该图片中没有对应类别的目标ground truth或者与所有ground truth重叠度都小于阈值
        else:
            fp[d] = 1.
        ## print('{}/{}  ID: {} tp:{:1.0f} fp:{:1.0f}'.format(d, nd, image_ids[d], tp[d], fp[d]))

    ## compute precision recall
    ## 按置信度取不同数量检测结果时的累计fp和tp
    ## np.cumsum([1, 2, 3, 4]) -> [1, 3, 6, 10]
    fp = np.cumsum(fp)
    tp = np.cumsum(tp)
    ## 召回率为占所有真实目标数量的比例,非减的,注意npos本身就排除了difficult,因此npos=tp+fn
    gt = float(npos)
    rec = tp / gt
    ## avoid divide by zero in case the first detection matches a difficult
    ## ground truth
    ## 精度为取的所有检测结果中tp的比例
    tp_fp = np.maximum(tp + fp, np.finfo(np.float64).eps)
    prec = tp / tp_fp
    error_rate = fp / tp_fp
    ## 计算recall-precise曲线下面积(严格来说并不是面积)
    ap = voc_ap(rec, prec, use_07_metric)
    print('测试数据集, 图片数量: {}张  gt_Label_num {} '.format(len(imagenames), gt))
    print(
        '人工标记gt   {:.0f} \n'
        '准确识别TP   {:.0f} \n'
        '误报FP       {:.0f} \n'
        '总共检出tpfp {:.0f} \n'
        '漏检FN       {:.0f}'
        .format(gt, tp[-1], fp[-1], tp_fp[-1], gt - tp[-1]))
    print(
        '误报率fp/tp_fp        {:.4f}\n'
        '正确率prec(tp/tp_fp)  {:.4f} \n'
        '查全率rec(tp/gt)      {:.4f} \n'
        'ap  {:.4f}'
        .format(error_rate[-1], prec[-1], rec[-1], ap))
    return rec, prec, ap

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).
    """
    if use_07_metric:
        ## 11 point metric
        ## 2010年以前按recall等间隔取11个不同点处的精度值做平均(0., 0.1, 0.2, …, 0.9, 1.0)
        ap = 0.
        for t in np.arange(0., 1.1, 0.1):
            if np.sum(rec >= t) == 0:
                p = 0
            else:
                ## 取最大值等价于2010以后先计算包络线的操作,保证precise非减
                p = np.max(prec[rec >= t])
            ap = ap + p / 11.
    else:
        ## correct AP calculation
        ## first append sentinel values at the end
        ## 2010年以后取所有不同的recall对应的点处的精度值做平均
        mrec = np.concatenate(([0.], rec, [1.]))
        mpre = np.concatenate(([0.], prec, [0.]))

        ## compute the precision envelope
        ## 计算包络线,从后往前取最大保证precise非减
        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
        ## 找出所有检测结果中recall不同的点
        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

另一种计算方式

def compute_ap(gt_boxes, gt_class_ids,
               pred_boxes, pred_class_ids, pred_scores,
               iou_threshold=0.5):
    """Compute Average Precision at a set IoU threshold (default 0.5).

    Returns:
    mAP: Mean Average Precision
    precisions: List of precisions at different class score thresholds.
    recalls: List of recall values at different class score thresholds.
    overlaps: [pred_boxes, gt_boxes] IoU overlaps.
    """
    ## Trim zero padding and sort predictions by score from high to low
    gt_boxes = trim_zeros(gt_boxes)
    pred_boxes = trim_zeros(pred_boxes)
    pred_scores = pred_scores[:pred_boxes.shape[0]]
    indices = np.argsort(pred_scores)[::-1]
    pred_boxes = pred_boxes[indices]
    pred_class_ids = pred_class_ids[indices]
    pred_scores = pred_scores[indices]

    ## Compute IoU overlaps [pred_boxes, gt_boxes]
    overlaps = compute_overlaps(pred_boxes, gt_boxes)

    ## Loop through ground truth boxes and find matching predictions
    match_count = 0
    pred_match = np.zeros([pred_boxes.shape[0]])
    gt_match = np.zeros([gt_boxes.shape[0]])
    for i in range(len(pred_boxes)):
        ## Find best matching ground truth box
        sorted_ixs = np.argsort(overlaps[i])[::-1]
        for j in sorted_ixs:
            ## If ground truth box is already matched, go to next one
            if gt_match[j] == 1:
                continue
            ## If we reach IoU smaller than the threshold, end the loop
            iou = overlaps[i, j]
            if iou < iou_threshold:
                break
            ## Do we have a match?
            if pred_class_ids[i] == gt_class_ids[j]:
                match_count += 1
                gt_match[j] = 1
                pred_match[i] = 1
                break

    ## Compute precision and recall at each prediction box step
    precisions = np.cumsum(pred_match) / (np.arange(len(pred_match)) + 1)
    recalls = np.cumsum(pred_match).astype(np.float32) / len(gt_match)

    ## Pad with start and end values to simplify the math
    precisions = np.concatenate([[0], precisions, [0]])
    recalls = np.concatenate([[0], recalls, [1]])

    ## Ensure precision values decrease but don't increase. This way, the
    ## precision value at each recall threshold is the maximum it can be
    ## for all following recall thresholds, as specified by the VOC paper.
    for i in range(len(precisions) - 2, -1, -1):
        precisions[i] = np.maximum(precisions[i], precisions[i + 1])

    ## Compute mean AP over recall range
    indices = np.where(recalls[:-1] != recalls[1:])[0] + 1
    mAP = np.sum((recalls[indices] - recalls[indices - 1]) *
                 precisions[indices])

    return mAP, precisions, recalls, overlaps

参考文献:
+++ 分类之性能评估指标
++多标签图像分类任务的评价方法-mAP_花心大罗博_新浪博客

深度学习: mAP (Mean Average Precision) - CSDN博客
++目标检测(一)目标检测评价指标 大雁与飞机 - CSDN博客

8. 其他评价指标

预测的准确率:这涉及到模型正确地预测新的或先前没见过的数据的类 标号能力。

速度:涉及到产生和使用模型的计算花费。

强壮性:这涉及给定噪声数据或具有空缺值的数据,模型正确预测的能力。

可伸缩性:这涉及给定大量的数据,有效的构造模型的能力。

可解释性:这涉及学习模型提供的理解和洞察的层次。

数据挖掘分类算法的评价指标


技术交流学习,请加QQ微信:631531977
目录