experiments / analyze_heuristic_position.py
ch-min's picture
Add files using upload-large-folder tool
3404d44 verified
#!/usr/bin/env python3
"""
2D Heuristic ๋‹ต์˜ ์„ ํƒ์ง€ ์œ„์น˜(A/B/C/D) ๋ถ„ํฌ ๋ถ„์„
๊ฐ€์„ค: FAR ์งˆ๋ฌธ์—์„œ 2D heuristic ๋‹ต(์ด๋ฏธ์ง€ ์œ„์ชฝ = ๊ฐ€์žฅ ๋จผ ๋ฌผ์ฒด)์ด
ํŠน์ • ์„ ํƒ์ง€ ์œ„์น˜(์˜ˆ: D)์— ํŽธ์ค‘๋˜์–ด ์žˆ์œผ๋ฉด, D bias๋ฅผ ๊ฐ€์ง„ ๋ชจ๋ธ์ด
FAR์—์„œ ๋” ๊ฐ•ํ•œ bias๋ฅผ ๋ณด์ด๋Š” ์ด์œ ๋ฅผ ์„ค๋ช…ํ•  ์ˆ˜ ์žˆ์Œ.
2D Heuristic ๋‹ต ์ •์˜:
- FAR: center_y๊ฐ€ ๊ฐ€์žฅ ์ž‘์€ ๋ฌผ์ฒด (์ด๋ฏธ์ง€ ์œ„์ชฝ = "๊ฐ€์žฅ ๋ฉ€๋‹ค")
- CLOSE: center_y๊ฐ€ ๊ฐ€์žฅ ํฐ ๋ฌผ์ฒด (์ด๋ฏธ์ง€ ์•„๋ž˜์ชฝ = "๊ฐ€์žฅ ๊ฐ€๊น๋‹ค")
Usage:
python experiments/analyze_heuristic_position.py
python experiments/analyze_heuristic_position.py -o experiments/heuristic_position_results.txt
"""
import argparse
import numpy as np
from datasets import load_dataset
from collections import Counter, defaultdict
import sys
class TeeWriter:
"""stdout์„ ํ„ฐ๋ฏธ๋„๊ณผ ํŒŒ์ผ์— ๋™์‹œ์— ์ถœ๋ ฅ"""
def __init__(self, filepath):
self.terminal = sys.stdout
self.file = open(filepath, 'w', encoding='utf-8')
def write(self, message):
self.terminal.write(message)
self.file.write(message)
def flush(self):
self.terminal.flush()
self.file.flush()
def close(self):
self.file.close()
return self.terminal
def get_bbox_center_y(bbox):
"""BBox [x, y, width, height] -> center y coordinate"""
return bbox[1] + bbox[3] / 2
def find_heuristic_answer(relation, objects, answer_options):
"""
2D heuristic์ด ์„ ํƒํ•  ๋‹ต์„ ์ฐพ๋Š”๋‹ค.
FAR: center_y๊ฐ€ ๊ฐ€์žฅ ์ž‘์€ ๋ฌผ์ฒด (์ด๋ฏธ์ง€ ์œ„์ชฝ = "๊ฐ€์žฅ ๋ฉ€๋‹ค")
CLOSE: center_y๊ฐ€ ๊ฐ€์žฅ ํฐ ๋ฌผ์ฒด (์ด๋ฏธ์ง€ ์•„๋ž˜์ชฝ = "๊ฐ€์žฅ ๊ฐ€๊น๋‹ค")
Returns:
heuristic_position: 0~3 (A~D), or None if not found
heuristic_name: ๋ฌผ์ฒด ์ด๋ฆ„
"""
bboxes = objects['bbox']
names = objects['name']
if len(bboxes) < 2:
return None, None
# ๊ฐ ๋ฌผ์ฒด์˜ center_y ๊ณ„์‚ฐ
center_ys = [(i, names[i], get_bbox_center_y(bboxes[i])) for i in range(len(bboxes))]
if relation == 'far':
# ๊ฐ€์žฅ ์ž‘์€ center_y (์ด๋ฏธ์ง€ ์œ„์ชฝ) = heuristic์ด "๊ฐ€์žฅ ๋ฉ€๋‹ค"๊ณ  ํŒ๋‹จ
heuristic_obj = min(center_ys, key=lambda x: x[2])
else: # close
# ๊ฐ€์žฅ ํฐ center_y (์ด๋ฏธ์ง€ ์•„๋ž˜์ชฝ) = heuristic์ด "๊ฐ€์žฅ ๊ฐ€๊น๋‹ค"๊ณ  ํŒ๋‹จ
heuristic_obj = max(center_ys, key=lambda x: x[2])
heuristic_name = heuristic_obj[1]
# answer_options์—์„œ ์ด ๋ฌผ์ฒด์˜ ์œ„์น˜(A/B/C/D) ์ฐพ๊ธฐ
if heuristic_name in answer_options:
position = answer_options.index(heuristic_name)
return position, heuristic_name
return None, heuristic_name
def main():
parser = argparse.ArgumentParser(description='2D Heuristic ๋‹ต์˜ ์„ ํƒ์ง€ ์œ„์น˜ ๋ถ„ํฌ ๋ถ„์„')
parser.add_argument('-o', '--output', type=str, help='Save results to file')
args = parser.parse_args()
if args.output:
tee = TeeWriter(args.output)
sys.stdout = tee
print("Loading EmbSpatial-Bench dataset...")
ds = load_dataset('FlagEval/EmbSpatial-Bench', split='test')
position_labels = ['A', 'B', 'C', 'D']
# ์ „์ฒด ํ†ต๊ณ„
heuristic_pos_far = [] # FAR์—์„œ heuristic ๋‹ต์˜ ์œ„์น˜
heuristic_pos_close = [] # CLOSE์—์„œ heuristic ๋‹ต์˜ ์œ„์น˜
gt_pos_far = [] # FAR์—์„œ GT ๋‹ต์˜ ์œ„์น˜
gt_pos_close = [] # CLOSE์—์„œ GT ๋‹ต์˜ ์œ„์น˜
# heuristic == GT์ธ์ง€ ์—ฌ๋ถ€
heuristic_is_gt_far = 0
heuristic_is_gt_close = 0
total_far = 0
total_close = 0
# ์ƒ์„ธ ๋ถ„์„์šฉ
not_found_count = 0
for item in ds:
relation = item['relation']
if relation not in ['far', 'close']:
continue
objects = item['objects']
answer_options = item['answer_options']
gt_answer_idx = item['answer']
heuristic_pos, heuristic_name = find_heuristic_answer(relation, objects, answer_options)
if heuristic_pos is None:
not_found_count += 1
continue
if relation == 'far':
total_far += 1
heuristic_pos_far.append(heuristic_pos)
gt_pos_far.append(gt_answer_idx)
if heuristic_pos == gt_answer_idx:
heuristic_is_gt_far += 1
else:
total_close += 1
heuristic_pos_close.append(heuristic_pos)
gt_pos_close.append(gt_answer_idx)
if heuristic_pos == gt_answer_idx:
heuristic_is_gt_close += 1
# ===== ๊ฒฐ๊ณผ ์ถœ๋ ฅ =====
print(f"\n{'='*70}")
print("2D Heuristic ๋‹ต์˜ ์„ ํƒ์ง€ ์œ„์น˜(A/B/C/D) ๋ถ„ํฌ ๋ถ„์„")
print(f"{'='*70}")
print(f"\nHeuristic ์ •์˜:")
print(f" FAR: center_y๊ฐ€ ๊ฐ€์žฅ ์ž‘์€ ๋ฌผ์ฒด (์ด๋ฏธ์ง€ ์œ„์ชฝ = '๊ฐ€์žฅ ๋ฉ€๋‹ค')")
print(f" CLOSE: center_y๊ฐ€ ๊ฐ€์žฅ ํฐ ๋ฌผ์ฒด (์ด๋ฏธ์ง€ ์•„๋ž˜์ชฝ = '๊ฐ€์žฅ ๊ฐ€๊น๋‹ค')")
print(f"\n๋งค์นญ ์‹คํŒจ: {not_found_count}๊ฐœ (answer_options์— heuristic ๋ฌผ์ฒด๊ฐ€ ์—†์Œ)")
for label, h_positions, g_positions, total, h_is_gt in [
('FAR', heuristic_pos_far, gt_pos_far, total_far, heuristic_is_gt_far),
('CLOSE', heuristic_pos_close, gt_pos_close, total_close, heuristic_is_gt_close),
('FAR+CLOSE', heuristic_pos_far + heuristic_pos_close,
gt_pos_far + gt_pos_close, total_far + total_close,
heuristic_is_gt_far + heuristic_is_gt_close),
]:
print(f"\n{'โ”€'*60}")
print(f" {label} (n={total})")
print(f"{'โ”€'*60}")
# Heuristic ๋‹ต ์œ„์น˜ ๋ถ„ํฌ
h_counter = Counter(h_positions)
print(f"\n [Heuristic ๋‹ต์˜ ์œ„์น˜ ๋ถ„ํฌ]")
print(f" {'Position':<10} {'Count':<10} {'Ratio':<10}")
for i, pl in enumerate(position_labels):
cnt = h_counter.get(i, 0)
ratio = cnt / total * 100 if total > 0 else 0
print(f" {pl:<10} {cnt:<10} {ratio:.1f}%")
h_std = np.std([h_counter.get(i, 0) / total * 100 for i in range(4)])
print(f" Std: {h_std:.1f}%p")
# GT ๋‹ต ์œ„์น˜ ๋ถ„ํฌ (์ฐธ๊ณ ์šฉ)
g_counter = Counter(g_positions)
print(f"\n [GT ๋‹ต์˜ ์œ„์น˜ ๋ถ„ํฌ]")
print(f" {'Position':<10} {'Count':<10} {'Ratio':<10}")
for i, pl in enumerate(position_labels):
cnt = g_counter.get(i, 0)
ratio = cnt / total * 100 if total > 0 else 0
print(f" {pl:<10} {cnt:<10} {ratio:.1f}%")
g_std = np.std([g_counter.get(i, 0) / total * 100 for i in range(4)])
print(f" Std: {g_std:.1f}%p")
# Heuristic == GT ๋น„์œจ
h_is_gt_total = heuristic_is_gt_far + heuristic_is_gt_close if label == 'FAR+CLOSE' else h_is_gt
print(f"\n Heuristic == GT: {h_is_gt}/{total} ({h_is_gt/total*100:.1f}%)")
print(f" โ†’ ์ด ๋น„์œจ์ด Consistent ์ƒ˜ํ”Œ ๋น„์œจ๊ณผ ์œ ์‚ฌํ•ด์•ผ ํ•จ")
# ===== Heuristic ๋‹ต ์œ„์น˜ vs GT ๋‹ต ์œ„์น˜ ๊ต์ฐจ ๋ถ„์„ =====
print(f"\n{'='*70}")
print("Heuristic ๋‹ต ์œ„์น˜ vs GT ๋‹ต ์œ„์น˜ ๊ต์ฐจ ๋ถ„์„")
print(f"{'='*70}")
for label, h_positions, g_positions, total in [
('FAR', heuristic_pos_far, gt_pos_far, total_far),
('CLOSE', heuristic_pos_close, gt_pos_close, total_close),
]:
print(f"\n {label}: Heuristic ์œ„์น˜๋ณ„ GT ์œ„์น˜ ๋ถ„ํฌ")
print(f" (ํ–‰: Heuristic ์œ„์น˜, ์—ด: GT ์œ„์น˜)")
print(f"\n {'Heur\\GT':<10}", end='')
for pl in position_labels:
print(f"{pl:<10}", end='')
print(f"{'Total':<10}")
print(f" {'โ”€'*50}")
cross = defaultdict(lambda: defaultdict(int))
for h, g in zip(h_positions, g_positions):
cross[h][g] += 1
for hi, hpl in enumerate(position_labels):
row_total = sum(cross[hi].values())
if row_total == 0:
continue
print(f" {hpl:<10}", end='')
for gi in range(4):
cnt = cross[hi][gi]
pct = cnt / row_total * 100 if row_total > 0 else 0
print(f"{cnt}({pct:.0f}%){'':<2}", end='')
print(f"{row_total}")
# ===== ํ•ต์‹ฌ ์š”์•ฝ =====
print(f"\n{'='*70}")
print("ํ•ต์‹ฌ ์š”์•ฝ")
print(f"{'='*70}")
far_h_counter = Counter(heuristic_pos_far)
close_h_counter = Counter(heuristic_pos_close)
far_max_pos = max(range(4), key=lambda i: far_h_counter.get(i, 0))
far_max_pct = far_h_counter.get(far_max_pos, 0) / total_far * 100
close_max_pos = max(range(4), key=lambda i: close_h_counter.get(i, 0))
close_max_pct = close_h_counter.get(close_max_pos, 0) / total_close * 100
print(f"\n FAR heuristic ๋‹ต ์ตœ๋‹ค ์œ„์น˜: {position_labels[far_max_pos]} ({far_max_pct:.1f}%)")
print(f" CLOSE heuristic ๋‹ต ์ตœ๋‹ค ์œ„์น˜: {position_labels[close_max_pos]} ({close_max_pct:.1f}%)")
far_d_pct = far_h_counter.get(3, 0) / total_far * 100
close_d_pct = close_h_counter.get(3, 0) / total_close * 100
print(f"\n FAR heuristic ๋‹ต์ด D ์œ„์น˜: {far_h_counter.get(3, 0)}/{total_far} ({far_d_pct:.1f}%)")
print(f" CLOSE heuristic ๋‹ต์ด D ์œ„์น˜: {close_h_counter.get(3, 0)}/{total_close} ({close_d_pct:.1f}%)")
if far_d_pct > 30:
print(f"\n โš  FAR์—์„œ heuristic ๋‹ต์ด D์— {far_d_pct:.1f}% ํŽธ์ค‘!")
print(f" โ†’ D bias ๋ชจ๋ธ์ด FAR์—์„œ heuristic์— ๋”ฐ๋ผ D๋ฅผ ์„ ํƒํ•˜๋Š” ๊ฒฝํ–ฅ ์„ค๋ช… ๊ฐ€๋Šฅ")
else:
print(f"\n FAR heuristic ๋‹ต์˜ D ์œ„์น˜ ๋น„์œจ์ด ๊ท ๋“ฑ({far_d_pct:.1f}%)์ด๋ฏ€๋กœ,")
print(f" D bias๊ฐ€ FAR์—์„œ ๋” ์‹ฌํ•œ ๊ฒƒ์€ ์„ ํƒ์ง€ ๋ฐฐ์น˜ ๋•Œ๋ฌธ์ด ์•„๋‹Œ ๋‹ค๋ฅธ ์š”์ธ์ผ ๊ฐ€๋Šฅ์„ฑ")
if args.output:
sys.stdout = tee.close()
print(f"Results saved to {args.output}")
if __name__ == '__main__':
main()