참고 : https://driip.me/15e1ad98-ad26-48c6-a0b8-43ef960a2d0e
Object detection에서 Precision과 Recall을 계산하는 것은 조금 더 복잡합니다. 일반적으로는 IoU(Intersection over Union)를 사용하여 각 예측된 bounding box와 실제 bounding box 간의 겹침을 계산합니다.
여기 간단한 예제 코드가 있습니다:
def calculate_iou(box1, box2):
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 = max(0, x2 - x1) * max(0, y2 - y1)
area_box1 = (box1[2] - box1[0]) * (box1[3] - box1[1])
area_box2 = (box2[2] - box2[0]) * (box2[3] - box2[1])
iou = intersection / float(area_box1 + area_box2 - intersection)
return iou
def calculate_precision_recall(predictions, ground_truths, threshold):
true_positive = 0
false_positive = 0
false_negative = 0
for prediction in predictions:
max_iou = max([calculate_iou(prediction, gt) for gt in ground_truths], default=0)
if max_iou >= threshold:
true_positive += 1
else:
false_positive += 1
false_negative = len(ground_truths) - true_positive
precision = true_positive / (true_positive + false_positive) if (true_positive + false_positive) != 0 else 0
recall = true_positive / (true_positive + false_negative) if (true_positive + false_negative) != 0 else 0
return precision, recall
# 예시 데이터
predictions = [(1, 1, 5, 5), (10, 10, 15, 15)]
ground_truths = [(1, 1, 6, 6), (10, 10, 14, 14)]
iou_threshold = 0.5
precision, recall = calculate_precision_recall(predictions, ground_truths, iou_threshold)
print(f'Precision: {precision:.2f}')
print(f'Recall: {recall:.2f}')
이 코드에서 predictions
는 모델이 예측한 bounding box 리스트이고, ground_truths
는 실제 bounding box 리스트입니다. iou_threshold
는 IoU가 이 값 이상이면 True Positive로 간주됩니다. 코드를 실행하면 Precision과 Recall이 출력됩니다.