2D Detection | F1 score 구하기
2023. 11. 8. 00:26ㆍDL
2D 객체 검출(2D object detection)에서 F1 점수(F1 score)를 계산하려면 예측(prediction)과 실제 탐지 결과(ground truth)의 일치 여부를 판단해야 합니다. 아래는 Python을 사용하여 F1 점수를 계산하는 예제 코드입니다. 먼저, 예측과 GT 객체 간의 IoU(Intersection over Union)를 계산하고, 그 기반으로 정밀도(Precision) 및 재현율(Recall)을 계산한 후 F1 점수를 구합니다.
def calculate_iou(box1, box2):
x1, y1, x2, y2 = box1
x3, y3, x4, y4 = box2
x_left = max(x1, x3)
y_top = max(y1, y3)
x_right = min(x2, x4)
y_bottom = min(y2, y4)
if x_right < x_left or y_bottom < y_top:
return 0.0
intersection_area = (x_right - x_left) * (y_bottom - y_top)
area_box1 = (x2 - x1) * (y2 - y1)
area_box2 = (x4 - x3) * (y4 - y3)
iou = intersection_area / (area_box1 + area_box2 - intersection_area)
return iou
def calculate_precision_recall(predictions, ground_truths, threshold=0.5):
true_positives = 0
false_positives = 0
false_negatives = 0
for pred in predictions:
is_matched = False
for gt in ground_truths:
iou = calculate_iou(pred, gt)
if iou >= threshold:
is_matched = True
break
if is_matched:
true_positives += 1
else:
false_positives += 1
for gt in ground_truths:
is_matched = False
for pred in predictions:
iou = calculate_iou(pred, gt)
if iou >= threshold:
is_matched = True
break
if not is_matched:
false_negatives += 1
precision = true_positives / (true_positives + false_positives)
recall = true_positives / (true_positives + false_negatives)
return precision, recall
def calculate_f1_score(predictions, ground_truths, threshold=0.5):
precision, recall = calculate_precision_recall(predictions, ground_truths, threshold)
if precision + recall == 0:
f1_score = 0
else:
f1_score = (2 * precision * recall) / (precision + recall)
return f1_score
# 예측(prediction)과 실제 탐지 결과(ground truth)를 정의
predictions = [(2, 2, 6, 6), (7, 7, 11, 11), (12, 12, 16, 16)]
ground_truths = [(1, 1, 5, 5), (6, 6, 10, 10), (12, 12, 16, 16)]
# F1 점수 계산
threshold = 0.5 # IoU 임계값 설정
f1_score = calculate_f1_score(predictions, ground_truths, threshold)
print("F1 Score:", f1_score)
이 코드는 calculate_iou
, calculate_precision_recall
, 그리고 calculate_f1_score
함수를 사용하여 F1 점수를 계산합니다. 이 예제에서는 IoU 임계값을 0.5로 설정했습니다. IoU 임계값을 조절하여 F1 점수를 다르게 설정할 수 있습니다.
'DL' 카테고리의 다른 글
Detection precision,recall,f1-score 계산 (Feat. 헝가리안 알고리즘) (0) | 2023.11.16 |
---|---|
2D Detection | precision, recall 그래프 그리기 (0) | 2023.11.08 |
2D Object Detection | pred 와 gt pair 찾기 (0) | 2023.11.08 |
특정 GPU 지정 / os.environ["CUDA_VISIBLE_DEVICES"] (0) | 2023.06.25 |
Object 2D Detection Label bbox 좌표(COCO, YOLO, KITTI, VOC) (0) | 2023.06.25 |