import numpy as np
class MeanAveragePrecision:
def __init__(self, num_classes):
self.num_classes = num_classes
self.precision_total = np.zeros((num_classes,))
self.recall_total = np.zeros((num_classes,))
self.average_precision = np.zeros((num_classes,))
self.cumulative_matches = np.zeros((num_classes,))
def update(self, predictions, ground_truths):
"""
Обновляет внутренние счетчики на основе предсказаний и истинных меток.
:param predictions: Список предсказаний модели в формате [class, confidence, (x1, y1, x2, y2)]
:param ground_truths: Список истинных меток в формате [class, (x1, y1, x2, y2)]
"""
for class_index in range(self.num_classes):
# Фильтруем предсказания и истинные метки по классу
class_predictions = [p for p in predictions if p[0] == class_index]
class_ground_truths = [g for g in ground_truths if g[0] == class_index]
# Сортируем предсказания по убыванию уверенности
class_predictions.sort(key=lambda x: x[1], reverse=True)
# Инициализируем счетчики для каждого класса
num_ground_truths = len(class_ground_truths)
matches = np.zeros((num_ground_truths,), dtype=bool)
# Проходим по предсказаниям и подсчитываем TP и FP
for prediction in class_predictions:
max_overlap = -np.inf
match_index = -1
for index, ground_truth in enumerate(class_ground_truths):
# Вычисляем IoU или другую метрику соответствия
iou = self._intersection_over_union(prediction[2], ground_truth[1])
if iou > max_overlap:
max_overlap = iou
match_index = index
# Определяем, является ли предсказание TP или FP
if max_overlap > 0.5 and not matches[match_index]:
matches[match_index] = True
self.cumulative_matches[class_index] += 1
precision = self.cumulative_matches[class_index] / (len(class_predictions) + 1e-16)
recall = self.cumulative_matches[class_index] / num_ground_truths
self.precision_total[class_index] += precision
self.recall_total[class_index] += recall
def compute(self):
"""
Вычисляет и возвращает mAP на основе накопленных значений Precision и Recall.
:return: mAP
"""
for class_index in range(self.num_classes):
# Вычисляем AP для каждого класса
precision = self.precision_total[class_index] / (self.recall_total[class_index] + 1e-16)
recall = self.recall_total[class_index] / (self.precision_total[class_index] + 1e-16)
self.average_precision[class_index] = self._compute_ap(recall, precision)
# Вычисляем mAP как среднее по всем классам
mean_ap = np.mean(self.average_precision)
return mean_ap
@staticmethod
def _intersection_over_union(box1, box2):
"""
Вычисляет IoU для двух bounding boxes.
:param box1: Первый bounding box в формате (x1, y1, x2, y2)
:param box2: Второй bounding box в формате (x1, y1, x2, y2)
:return: IoU в виде float
"""
# Вычисляем координаты пересечения
x1 = max(box1[0], box2[0])
y1 = max(box1[1], box2[1])
x2 = min(box1[2], box2[2])
y2 = min(box1[3], box2[3])
# Вычисляем площадь пересечения
intersection_area = max(x2 - x1, 0) * max(y2 - y1, 0)
# Вычисляем площади двух bounding boxes
box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])
box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])
# Вычисляем IoU
iou = intersection_area / float(box1_area + box2_area - intersection_area)
return iou
@staticmethod
def _compute_ap(recall, precision):
"""
Вычисляет AP на основе значений Recall и Precision.
:param recall: Список значений Recall
:param precision: Список значений Precision
:return: AP
"""
# Вычисляем AP как площадь под Precision-Recall кривой
ap = 0.0
for i in range(len(recall) - 1):
ap += precision[i] * (recall[i + 1] - recall[i])
return ap
# Пример использования
if __name__ == "__main__":
# Создаем экземпляр класса для 3 классов
map_calculator = MeanAveragePrecision(num_classes=3)
# Пример предсказаний и истинных меток
predictions = [
[0, 0.9, (100, 100, 200, 200)],
[1, 0.8, (50, 50, 150, 150)],
[2, 0.7, (20, 20, 120, 120)]
]
ground_truths = [
[0, (110, 110, 190, 190)],
[1, (60, 60, 140, 140)],
[2, (30, 30, 110, 110)]
]
# Обновляем счетчики
map_calculator.update(predictions, ground_truths)
# Вычисляем и выводим mAP
mean_ap = map_calculator.compute()
print(f"Mean Average Precision (mAP): {mean_ap}")