Files
Negotiation_daegu/eval/10_persona/aggregate.py
T
민헌andClaude Opus 5 50016ebd06 ③⑩ 단독측정 정본 반영 + 테스트데이터 지표별 명명 + ⑩ 실행기 경로 정리
③⑩ 을 09-10 단독측정으로 교체 (지표별 독립 실행기 negotiation.py, gpt-4o 1종 300건)
  ③ 5.877 → 5.784% · ⑩ 98.23 → 98.36% (253세션 1,086매칭)
  ①의 협상 기록 재집계 방식은 aggregate.py 보조 경로로 유지

run-eval.sh ⑩ 경로를 ③ 과 같은 단독측정으로 교체 (M10_REAGG=1 이면 옛 재집계)
eval/10_persona/aggregate.py
  - --out 추가 — 시험 실행이 정본 result.json·detail.jsonl 을 덮지 않게
  - 세션 대응 키를 기록의 session_id 우선으로 (EVAL-case_id 하드코딩 시
    EVAL10-* 기록이 ①의 옛 로그와 잘못 짝지어져 오답을 냈다. ① 기록은 폴백 동작 동일)

testdata 명명 규칙 <지표번호>_data_<이름>, 둘 이상이 쓰면 00_ (공용)
  testset_300 → 00_data_testset_300 · product_names → 00_data_product_names
  2_total_data → 02_data_total · 7_testset_10272 → 07_data_testset_10272
  8_items1000_master → 08_data_items1000_master
  생성기·룰(.py)은 번호 없음. 끝난 측정의 기록에는 옛 이름이 남아 있어
  testdata/README.md 에 옛↔새 대응표를 둔다

eval/SUMMARY.md 를 정본 수치와 일치시킴
③ 100건 파일럿 실행원본은 저장소 밖 _archive_20260910_실행원본/ 으로 이동

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-11 11:12:32 +09:00

158 lines
7.5 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 "<① 실행 원본>/detail_*.jsonl" (원본은 저장소 밖 NEGO_DOCS/_archive_20260909_실행원본/01_win_rate/ 에 보관)
python aggregate.py --details "<...>" --out /tmp/x 정본을 건드리지 않고 그 폴더에 산출
출력: (기본 이 스크립트 폴더 — --out 으로 옮길 수 있다)
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)
ap.add_argument("--out", type=Path, default=HERE,
help="산출 위치 (기본: 이 스크립트 폴더 = 정본). 시험 실행은 다른 경로를 준다")
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_id 가 있으면 그것을 쓴다 — 단독측정 기록은 접두가 EVAL10 이라
# EVAL-n 으로 가정하면 ①의 옛 로그와 엉뚱하게 짝지어진다.
# ①의 본측정 기록에는 session_id 필드가 없어 옛 규칙(EVAL-case_id)으로 되돌아간다.
session = row.get("session_id") or 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"
args.out.mkdir(parents=True, exist_ok=True)
meta_dir = args.out / "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),
"제외_정의불가_세션": undefined_sessions,
"제외사유": "초기 제안가 ≤ 목표가 — 긴장도 분모(초기 제안가 − 목표가)가 0 이하라 정의 불가",
"매칭 라운드": matched,
"미매칭 라운드": missing,
"평균오차": round(overall, 4) if overall is not None else None,
"페르소나_적용분포": dict(persona_counter),
"페르소나정확도_pct": accuracy_pct,
"목표_pct": args.target,
"verdict": verdict,
"상세": "data/persona_meta.json",
}
(args.out / "result.json").write_text(json.dumps(out, ensure_ascii=False, indent=1),
encoding="utf-8")
with open(args.out / "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()