不同的计算机视觉问题,对两类错误有不同的偏好,常常在某一类错误不多于一定阈值的情况下,努力减少另一类错误。在目标检测中,mAP(mean Average Precision)作为一个统一的指标将这两种错误兼顾考虑。
很多时候我们会有多个混淆矩阵,例如进行多次训练/测试,每次都能得到一个混淆矩阵;或者是在多个数据集上进行训练/测试,希望估计算法的”全局“性能;又或者是执行多分类任务,每两两类别的组合都对应一个混淆矩阵;…总而来说,我们希望能在
n
n
n 个二分类混淆矩阵上综合考虑查准率和查全率。
一种直接的做法是先在各混淆矩阵上分别计算出查准率和查全率,记为
(
P
1
,
R
1
)
,
(
P
2
,
R
2
)
,
.
.
.
,
(
P
n
,
R
n
)
(P_1,R_1),(P_2,R_2),...,(P_n,R_n)
(P1?,R1?),(P2?,R2?),...,(Pn?,Rn?) 然后取平均,这样得到的是”宏查准率(Macro-P)“、”宏查准率(Macro-R)“及对应的”宏
F
1
F1
F1(Macro-F1)“:
M
a
c
r
o
?
P
=
1
n
∑
i
=
1
n
P
i
Macro\ P = \frac{1}{n}\sum_{i=1}^{n}P_i
Macro?P=n1?i=1∑n?Pi?
M
a
c
r
o
?
R
=
1
n
∑
i
=
1
n
R
i
Macro\ R = \frac{1}{n}\sum_{i=1}^{n}R_i
Macro?R=n1?i=1∑n?Ri?
M
a
c
r
o
?
F
1
=
2
×
M
a
c
r
o
?
P
×
M
a
c
r
o
?
R
M
a
c
r
o
?
P
+
M
a
c
r
o
?
R
Macro\ F1 = \frac{2 \times Macro\ P\times Macro\ R}{Macro\ P + Macro\ R}
Macro?F1=Macro?P+Macro?R2×Macro?P×Macro?R?
另一种做法是将各混淆矩阵对应元素进行平均,得到
T
P
、
F
P
、
T
N
、
F
N
TP、FP、TN、FN
TP、FP、TN、FN 的平均值,再基于这些平均值计算出”微查准率“(Micro-P)、”微查全率“(Micro-R)和”微
F
1
F1
F1“(Mairo-F1)
M
i
c
r
o
?
P
=
T
P
 ̄
T
P
 ̄
+
F
P
 ̄
Micro\ P = \frac{\overline{TP}}{\overline{TP}+\overline{FP}}
Micro?P=TP+FPTP?
M
i
c
r
o
?
R
=
T
P
 ̄
T
P
 ̄
+
F
N
 ̄
Micro\ R = \frac{\overline{TP}}{\overline{TP}+\overline{FN}}
Micro?R=TP+FNTP?
M
i
c
r
o
?
F
1
=
2
×
M
i
c
r
o
?
P
×
M
i
c
r
o
?
R
M
a
c
r
o
P
+
M
i
c
r
o
?
R
Micro\ F1 = \frac{2 \times Micro\ P\times Micro\ R}{MacroP+Micro\ R}
Micro?F1=MacroP+Micro?R2×Micro?P×Micro?R?
1.4,PR 曲线
精准率和召回率的关系可以用一个 P-R 图来展示,以查准率 P 为纵轴、查全率 R 为横轴作图,就得到了查准率-查全率曲线,简称 P-R 曲线,PR 曲线下的面积定义为 AP:
mAP 常作为目标检测算法的评价指标,具体来说就是,对于每张图片检测模型会输出多个预测框(远超真实框的个数),我们使用 IoU (Intersection Over Union,交并比)来标记预测框是否预测准确。标记完成后,随着预测框的增多,查全率 R 总会上升,在不同查全率 R 水平下对准确率 P 做平均,即得到 AP,最后再对所有类别按其所占比例做平均,即得到 mAP 指标。
2.2,近似计算AP
知道了AP 的定义,下一步就是理解AP计算的实现,理论上可以通过积分来计算AP,公式如下:
A
P
=
∫
0
1
P
(
r
)
d
r
AP=\int_0^1 P(r) dr
AP=∫01?P(r)dr 但通常情况下都是使用近似或者插值的方法来计算
A
P
AP
AP。
A
P
=
∑
k
=
1
N
P
(
k
)
Δ
r
(
k
)
AP = \sum_{k=1}^{N}P(k)\Delta r(k)
AP=k=1∑N?P(k)Δr(k)
近似计算
A
P
AP
AP (approximated average precision),这种计算方式是 approximated 形式的;
很显然位于一条竖直线上的点对计算
A
P
AP
AP 没有贡献;
这里
N
N
N 为数据总量,
k
k
k 为每个样本点的索引,
Δ
r
(
k
)
=
r
(
k
)
?
r
(
k
?
1
)
Δr(k)=r(k)?r(k?1)
Δr(k)=r(k)?r(k?1)。
近似计算AP 和绘制 PR 曲线代码如下:
import numpy as np
import matplotlib.pyplot as plt
class_names =["car","pedestrians","bicycle"]defdraw_PR_curve(predict_scores, eval_labels, name, cls_idx=1):"""calculate AP and draw PR curve, there are 3 types
Parameters:
@all_scores: single test dataset predict scores array, (-1, 3)
@all_labels: single test dataset predict label array, (-1, 3)
@cls_idx: the serial number of the AP to be calculated, example: 0,1,2,3...
"""# print('sklearn Macro-F1-Score:', f1_score(predict_scores, eval_labels, average='macro'))global class_names
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(15,10))# Rank the predicted scores from large to small, extract their corresponding index(index number), and generate an array
idx = predict_scores[:, cls_idx].argsort()[::-1]
eval_labels_descend = eval_labels[idx]
pos_gt_num = np.sum(eval_labels == cls_idx)# number of all gt
predict_results = np.ones_like(eval_labels)
tp_arr = np.logical_and(predict_results == cls_idx, eval_labels_descend == cls_idx)# ndarray
fp_arr = np.logical_and(predict_results == cls_idx, eval_labels_descend != cls_idx)
tp_cum = np.cumsum(tp_arr).astype(float)# ndarray, Cumulative sum of array elements.
fp_cum = np.cumsum(fp_arr).astype(float)
precision_arr = tp_cum /(tp_cum + fp_cum)# ndarray
recall_arr = tp_cum / pos_gt_num
ap =0.0
prev_recall =0for p, r inzip(precision_arr, recall_arr):
ap += p *(r - prev_recall)# pdb.set_trace()
prev_recall = r
print("------%s, ap: %f-----"%(name, ap))
fig_label ='[%s, %s] ap=%f'%(name, class_names[cls_idx], ap)
ax.plot(recall_arr, precision_arr, label=fig_label)
ax.legend(loc="lower left")
ax.set_title("PR curve about class: %s"%(class_names[cls_idx]))
ax.set(xticks=np.arange(0.,1,0.05), yticks=np.arange(0.,1,0.05))
ax.set(xlabel="recall", ylabel="precision", xlim=[0,1], ylim=[0,1])
fig.savefig("./pr-curve-%s.png"% class_names[cls_idx])
plt.close(fig)
2.3,插值计算 AP
插值计算(Interpolated average precision)
A
P
AP
AP 的公式的演变过程这里不做讨论,详情可以参考这篇文章,我这里的公式和图也是参考此文章的。11 点插值计算方式计算
A
P
AP
AP 公式如下:
这里因为参与计算的只有 11 个点,所以
K
=
11
K=11
K=11,称为 11 points_Interpolated,
k
k
k 为阈值索引
P
i
n
t
e
r
p
(
k
)
P_{interp}(k)
Pinterp?(k) 取第
k
k
k 个阈值所对应的样本点之后的样本中的最大值,只不过这里的阈值被限定在了
0
,
0.1
,
0.2
,
…
,
1.0
{0,0.1,0.2,…,1.0}
0,0.1,0.2,…,1.0 范围内。
从曲线上看,真实 AP< approximated AP < Interpolated AP,11-points Interpolated AP 可能大也可能小,当数据量很多的时候会接近于 Interpolated AP,与 Interpolated AP 不同,前面的公式中计算 AP 时都是对 PR 曲线的面积估计,PASCAL 的论文里给出的公式就更加简单粗暴了,直接计算11 个阈值处的 precision 的平均值。PASCAL 论文给出的 11 点计算 AP 的公式如下。
1, 在给定 recal 和 precision 的条件下计算 AP:
defvoc_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
ap =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 end
mrec = np.concatenate(([0.], rec,[1.]))
mpre = np.concatenate(([0.], prec,[0.]))# compute the precision envelopefor i inrange(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:
defparse_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 objects
defvoc_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 gtifnot os.path.isdir(cachedir):
os.mkdir(cachedir)
cachefile = os.path.join(cachedir,'%s_annots.pkl'% imagesetfile)# read list of imageswithopen(imagesetfile,'r')as f:
lines = f.readlines()
imagenames =[x.strip()for x in lines]ifnot os.path.isfile(cachefile):# load annotations
recs ={}for i, imagename inenumerate(imagenames):
recs[imagename]= parse_rec(annopath.format(imagename))if i %100==0:print('Reading annotation for {:d}/{:d}'.format(
i +1,len(imagenames)))# saveprint('Saving cached annotations to {:s}'.format(cachefile))withopen(cachefile,'wb')as f:
pickle.dump(recs, f)else:# loadwithopen(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 =0for 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)withopen(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 FPsfor d inrange(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:ifnot R['difficult'][jmax]:ifnot R['det'][jmax]:
tp[d]=1.
R['det'][jmax]=1else:
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, ap
2.4,mAP 计算方法
因为
m
A
P
mAP
mAP 值的计算是对数据集中所有类别的
A
P
AP
AP 值求平均,所以我们要计算
m
A
P
mAP
mAP,首先得知道某一类别的
A
P
AP
AP 值怎么求。不同数据集的某类别的
A
P
AP
AP 计算方法大同小异,主要分为三种:
(1)在 VOC2007,只需要选取当
R
e
c
a
l
l
>
=
0
,
0.1
,
0.2
,
.
.
.
,
1
Recall >= 0, 0.1, 0.2, ..., 1
Recall>=0,0.1,0.2,...,1 共 11 个点时的 Precision 最大值,然后
A
P
AP
AP 就是这 11 个 Precision 的平均值,
m
A
P
mAP
mAP 就是所有类别
A
P
AP
AP 值的平均。VOC 数据集中计算
A
P
AP
AP 的代码(用的是插值计算方法,代码出自py-faster-rcnn仓库)
(2)在 VOC2010 及以后,需要针对每一个不同的 Recall 值(包括 0 和 1),选取其大于等于这些 Recall 值时的 Precision 最大值,然后计算 PR 曲线下面积作为
A
P
AP
AP 值,
m
A
P
mAP
mAP 就是所有类别
A
P
AP
AP 值的平均。
(3)COCO 数据集,设定多个 IOU 阈值(0.5-0.95, 0.05 为步长),在每一个 IOU 阈值下都有某一类别的 AP 值,然后求不同 IOU 阈值下的 AP 平均,就是所求的最终的某类别的 AP 值。