Files
Negotiation_daegu/eval/10_persona/aggregate.py
T
민헌andClaude Opus 5 97aeff6ac4 ⑩ result.json을 측정값 중심으로 정리 + 실행 증적 추가
②③⑥⑦과 같은 형식으로 통일. 값 변화 없음 (98.23% PASS, 268세션 1,195라운드).

- result.json: 세션 수·매칭 라운드·평균오차·정확도·목표·판정 (평평한 7키)
- data/persona_meta.json 신설: 산식·예측/실제 정의·표본 추림·페르소나 분포
  (정의불가 세션 32건 제외를 "제외_정의불가_세션"으로 명시 — 300→268 경로가 드러남)
- 평균오차 0.0177 기재 — 정확도 = (1 − 평균오차) × 100 을 되짚어 검산 가능
- log.txt 신설: Azure 실행 환경·명령·시각 (⑨ meta.json과 같은 취지)

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014sLpiFCT7Lj78iLwPbVx7a
2026-09-07 15:42:50 +09:00

146 lines
6.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""⑩ 실시간 페르소나 정확도 — 집계기 (2026-08-28 확정 설계).
계획서 산식 그대로:
정확도 = 1 − mean(시나리오별 mean(|실제 긴장도 − 예측 긴장도|)) (시나리오 = 협상 세션)
정의 (확정):
- 실제 긴장도 (사후, 하네스 가격 기록으로 산출) = clip((제안가 − 목표가) / (초기제안가 − 목표가))
- 예측 긴장도 (서버 실시간 계측) = 단계 변수인 지표점수(1~99 정수)에서 역산한 추정치.
이 수치가 페르소나(저/중/고 3구간) 적용에 실제로 사용된다 — 계획서 "수치에 따라 페르소나 적용".
지표점수의 정수 양자화 때문에 실제값과 독립적인 오차가 존재한다 (측정 건전성 근거).
병합: (session_id, iteration) — 서버 로그의 신형 행(persona 필드 보유)만 사용, 중복 키는 최신 우선.
사용:
python aggregate.py --details "../01_win_rate/본측정300_azure_20260901/detail_*.jsonl"
출력: data/persona_meta.json 산식·정의·표본 추림·페르소나 분포
detail.jsonl 라운드별 예측·실제·오차
result.json 세션 수 + 정확도 + PASS/FAIL
"""
import argparse
import glob
import json
from collections import Counter
from pathlib import Path
HERE = Path(__file__).parent
DEFAULT_TENSION = HERE.parent.parent / "server" / "data" / "tension_log.jsonl"
def clip01(v: float) -> float:
return max(0.0, min(1.0, v))
def load_predicted(path: str):
"""(session_id, iteration) → {predicted, persona}. 신형 행만, 중복은 최신 우선."""
pred = {}
for line in Path(path).read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
r = json.loads(line)
if "persona" not in r: # 구형(잠정 산식 시절) 행 제외
continue
pred[(r["session_id"], r["iteration"])] = r
return pred
def actual_entries(detail_row: dict):
"""하네스 detail 한 건에서 (iteration, 실제 긴장도) 재구성 —
동적 스텝 진입(res_step == '가격협상') 시점의 제안가 기준."""
target = detail_row.get("target")
initial = detail_row.get("initial_offer")
if not target or not initial or float(initial) <= float(target):
return None # 긴장도 정의 불가 (초기제안가 ≤ 목표가)
out = []
k = 0
for rd in detail_row.get("rounds", []):
if rd.get("res_step") == "가격협상" and rd.get("req_price") is not None:
actual = clip01((float(rd["req_price"]) - float(target))
/ (float(initial) - float(target)))
out.append((k, actual))
k += 1
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--tension-log", default=str(DEFAULT_TENSION))
ap.add_argument("--details", required=True,
help="하네스 detail 파일 glob (예: '../01_win_rate/본측정_*/detail_*.jsonl')")
ap.add_argument("--target", type=float, default=96.0)
args = ap.parse_args()
pred = load_predicted(args.tension_log)
session_diffs = {}
persona_counter = Counter()
matched = missing = undefined_sessions = 0
detail_out = []
for path in sorted(glob.glob(args.details)):
for line in Path(path).read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
row = json.loads(line)
if str(row.get("outcome", "")).startswith("오류"):
continue
entries = actual_entries(row)
if entries is None:
undefined_sessions += 1
continue
session = f"EVAL-{row['case_id']}"
for k, actual in entries:
p = pred.get((session, k))
if p is None:
missing += 1
continue
matched += 1
diff = abs(p["predicted"] - actual)
session_diffs.setdefault(session, []).append(diff)
persona_counter[p["persona"]] += 1
detail_out.append({"session_id": session, "iteration": k,
"predicted": p["predicted"], "actual": round(actual, 4),
"diff": round(diff, 4), "indicator": p.get("indicator"),
"persona": p["persona"]})
session_means = {s: sum(d) / len(d) for s, d in session_diffs.items()}
overall = (sum(session_means.values()) / len(session_means)) if session_means else None
accuracy_pct = round(100 * (1 - overall), 2) if overall is not None else None
verdict = "PASS" if accuracy_pct is not None and accuracy_pct >= args.target else "FAIL"
meta_dir = HERE / "data"
meta_dir.mkdir(exist_ok=True)
(meta_dir / "persona_meta.json").write_text(json.dumps({
"산식": "1 − mean(시나리오별 mean(|실제 − 예측|)) — 계획서 원문 산식 (시나리오=세션)",
"예측": "서버 실시간: 지표점수(1~99)→긴장도 역산 추정치 (페르소나 적용에 사용된 수치)",
"실제": "사후: clip((제안가−목표가)/(초기제안가−목표가)) — 하네스 가격 기록 기준",
"표본추림": {"집계_세션": len(session_means), "매칭_라운드": matched,
"미매칭_라운드": missing,
"제외_정의불가_세션(초기제안가≤목표가)": undefined_sessions},
"페르소나_적용분포": dict(persona_counter),
"평균오차": round(overall, 4) if overall is not None else None,
"목표_pct": args.target,
"verdict": verdict,
}, ensure_ascii=False, indent=1), encoding="utf-8")
out = {
"세션 수": len(session_means),
"매칭 라운드": matched,
"평균오차": round(overall, 4) if overall is not None else None,
"페르소나정확도_pct": accuracy_pct,
"목표_pct": args.target,
"verdict": verdict,
"상세": "data/persona_meta.json",
}
(HERE / "result.json").write_text(json.dumps(out, ensure_ascii=False, indent=1),
encoding="utf-8")
with open(HERE / "detail.jsonl", "w", encoding="utf-8") as f:
for r in detail_out:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
print(json.dumps(out, ensure_ascii=False, indent=1))
if __name__ == "__main__":
main()