#!/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()