mAP@0.5 的python实现
时间: 2023-06-14 21:05:46 浏览: 134
mAP(mean Average Precision)是目标检测中常用的评价指标之一,用于衡量模型在不同类别上的平均精度。在mAP中,我们通常选择IoU(Intersection over Union)的阈值为0.5。
下面是mAP@0.5的Python实现代码:
```python
def calculate_iou(box1, box2):
"""
计算两个框之间的IoU
"""
x1, y1, w1, h1 = box1
x2, y2, w2, h2 = box2
intersect_x1 = max(x1, x2)
intersect_y1 = max(y1, y2)
intersect_x2 = min(x1 + w1, x2 + w2)
intersect_y2 = min(y1 + h1, y2 + h2)
intersect_w = max(0, intersect_x2 - intersect_x1)
intersect_h = max(0, intersect_y2 - intersect_y1)
intersect_area = intersect_w * intersect_h
box1_area = w1 * h1
box2_area = w2 * h2
iou = intersect_area / float(box1_area + box2_area - intersect_area)
return iou
def calculate_ap(precision, recall):
"""
计算AP(Average Precision)
"""
mrec = np.concatenate(([0.], recall, [1.]))
mpre = np.concatenate(([0.], precision, [0.]))
# 计算精确率下降的点
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
# 找到召回率变化的位置
i = np.where(mrec[1:] != mrec[:-1])[0]
# 计算AP
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
return ap
def calculate_map(gt_boxes, pred_boxes, iou_threshold=0.5):
"""
计算mAP(mean Average Precision)
"""
num_classes = len(gt_boxes)
aps = []
for class_id in range(num_classes):
class_gt_boxes = gt_boxes[class_id]
class_pred_boxes = pred_boxes[class_id]
num_gt_boxes = len(class_gt_boxes)
num_pred_boxes = len(class_pred_boxes)
# 初始化precision和recall
precision = np.zeros(num_pred_boxes)
recall = np.zeros(num_pred_boxes)
# 计算每个预测框的IoU和得分
iou_scores = np.zeros((num_pred_boxes, num_gt_boxes))
scores = np.zeros(num_pred_boxes)
for i in range(num_pred_boxes):
for j in range(num_gt_boxes):
iou_scores[i][j] = calculate_iou(class_pred_boxes[i], class_gt_boxes[j])
scores[i] = class_pred_boxes[i][4]
# 按照得分排序
sorted_indices = np.argsort(scores)[::-1]
# 计算precision和recall
for i in range(num_pred_boxes):
index = sorted_indices[i]
if iou_scores[index].max() >= iou_threshold:
precision[i] = 1.
recall[i] = (i + 1) / float(num_gt_boxes)
# 计算AP
ap = calculate_ap(precision, recall)
aps.append(ap)
# 计算mAP
map = np.mean(aps)
return map
```
以上代码中,`gt_boxes`是一个列表,其中每个元素都是一个二维数组,表示某类别的所有ground truth boxes。`pred_boxes`也是一个列表,其中每个元素都是一个二维数组,表示某类别的所有predicted boxes。每个二维数组中,每个元素都是一个长度为5的一维数组,表示一个框的坐标和得分。
在计算mAP时,我们首先遍历每个类别,然后计算每个类别的AP。对于每个类别,我们计算每个predicted box与所有ground truth boxes之间的IoU,并将IoU大于阈值的predicted box视为true positive。然后按照predicted box的得分排序,计算precision和recall,并计算AP。最后,计算所有类别的AP的平均值,即为mAP。
阅读全文