gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
Можешь написать алгоритм подсчета mAP50-95 на основе предсказаний?
- User
Можешь написать алгоритм подсчета mAP50-95 на основе предсказаний?
- Assistant
Можешь написать алгоритм подсчета mAP50-95 на основе предсказаний?
Конечно! Ниже приведён пример алгоритма для вычисления метрики mAP@50:95 (mean Average Precision при IoU порогах от 0.5 до 0.95 с шагом 0.05), которая часто используется в задачах объектного детектирования (например, в COCO evaluation).
[x1, y1, x2, y2, confidence_score, class_id].[x1, y1, x2, y2, class_id].[0.5, 0.55, 0.6, ..., 0.95].import numpy as np
def iou(boxA, boxB):
# box = [x1, y1, x2, y2]
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], boxB[1])
xB = min(boxA[2], boxB[2])
yB = min(boxA[3], boxB[3])
interArea = max(0, xB - xA) * max(0, yB - yA)
boxAArea = (boxA[2]-boxA[0]) * (boxA[3]-boxA[1])
boxBArea = (boxB[2]-boxB[0]) * (boxB[3]-boxB[1])
return interArea / float(boxAArea + boxBArea - interArea + 1e-6)
def compute_ap(recall, precision):
"""
Вычисление AP по кривой precision-recall.
Используем интерполяцию по COCO:
AP = среднее precision по 101 точке recall от 0.0 до 1.0 с шагом 0.01
"""
mrec = np.concatenate(([0.0], recall, [1.0]))
mpre = np.concatenate(([0.0], precision, [0.0]))
for i in range(len(mpre)-2, -1, -1):
mpre[i] = max(mpre[i], mpre[i+1])
recall_points = np.linspace(0,1,101)
ap = 0.0
for t in recall_points:
p = max(mpre[mrec >= t], default=0)
ap += p / 101
return ap
def evaluate_map(gt_dict, pred_dict, iou_thresholds=None):
"""
gt_dict, pred_dict: dict
ключ - image_id
значение - list of objects
GT: [x1,y1,x2,y2,class_id]
Pred: [x1,y1,x2,y2,score,class_id]
iou_thresholds: list
Список IoU порогов для вычисления AP
Возвращает: mAP (средний AP по всем классам и IoU)
"""
if iou_thresholds is None:
iou_thresholds = np.arange(0.5, 1.0, 0.05)
all_classes = set()
for objs in gt_dict.values():
for obj in objs:
all_classes.add(obj[4])
for objs in pred_dict.values():
for obj in objs:
all_classes.add(obj[5])
average_precisions = []
for iou_thresh in iou_thresholds:
ap_per_class = []
for cls in all_classes:
# Собираем один список всех GT для cls
gt_instances = {}
npos = 0
for img_id, gt_objs in gt_dict.items():
# Выбираем GT классу cls
cls_gt = [obj for obj in gt_objs if obj[4] == cls]
gt_instances[img_id] = {
'boxes': [obj[:4] for obj in cls_gt],
'detected': [False]*len(cls_gt)
}
npos += len(cls_gt)
# Собираем все предсказания для класса cls
detections = []
for img_id, pred_objs in pred_dict.items():
for obj in pred_objs:
if obj[5] == cls:
detections.append({
'image_id': img_id,
'bbox': obj[:4],
'score': obj[4]
})
# Сортируем по убыванию confidence
detections.sort(key=lambda x: x['score'], reverse=True)
tp = np.zeros(len(detections))
fp = np.zeros(len(detections))
for idx, det in enumerate(detections):
img_id = det['image_id']
pred_box = det['bbox']
max_iou = 0
max_iou_idx = -1
if img_id in gt_instances:
gt_boxes = gt_instances[img_id]['boxes']
detected_flags = gt_instances[img_id]['detected']
for i, gt_box in enumerate(gt_boxes):
iou_val = iou(pred_box, gt_box)
if iou_val > max_iou:
max_iou = iou_val
max_iou_idx = i
if max_iou >= iou_thresh:
if not gt_instances[img_id]['detected'][max_iou_idx]:
tp[idx] = 1
gt_instances[img_id]['detected'][max_iou_idx] = True
else:
fp[idx] = 1 # дубликат
else:
fp[idx] = 1 # ложное срабатывание
# Калькуляция precision-recall
fp = np.cumsum(fp)
tp = np.cumsum(tp)
recall = tp / (npos + 1e-6)
precision = tp / (tp + fp + 1e-6)
ap = compute_ap(recall, precision)
ap_per_class.append(ap)
mean_ap = np.mean(ap_per_class) if ap_per_class else 0
average_precisions.append(mean_ap)
return np.mean(average_precisions)
gt_dict = {
'img1': [ [50,50,100,100, 1], [120,120,170,170, 2] ],
'img2': [ [30,30,80,80, 1] ]
}
pred_dict = {
'img1': [ [48,48,102,102, 0.9, 1], [118,118,172,172, 0.8, 2], [60,60,110,110, 0.4, 1] ],
'img2': [ [28,28,78,78, 0.95, 1], [10,10,50,50, 0.3, 2] ]
}
map_value = evaluate_map(gt_dict, pred_dict)
print("mAP@50:95 =", map_value)
Если нужно, могу помочь адаптировать код под ваши конкретные данные или дальнейшую оптимизацию.
Если есть вопросы — спрашивайте!
Not yet included in a published release.