⑦ 협상데이터 수집 - collect.py 추가 — ①의 협상 실행기를 재사용해 챗봇을 돌리고 계약 기록을 data/contracts.jsonl 에 축적 (재실행 시 수집분 건너뜀, data/.collect.lock 으로 동시 실행 차단) - run.py 에 ProfiledOpponent 추가 — gpt-4o 실측 409건 분포로 보정한 규칙 기반 공급사(프로파일 4종, seed 고정) 검증: 같은 409 케이스에서 첫 제안·양보폭·합의가·협상률 일치, 카드 수락과 목표 달성은 6~7%p 보수적 - 시뮬레이터 상대로 10,272건 수집 → 목표 10,000건 PASS - aggregate.py 간소화 — result.json 은 최종 집계·목표 건수·판정 3개만. 계획서 평가방법이 기간 환산을 규정하지 않으므로 연환산 제거, 건수는 고유 session_id 수로 집계 저장소 정리 - 각 eval/<지표>/ 에 측정 코드·result.json·provenance.md 와 최종 데이터 산출물만 남김 - 실행 원본·로그·중간 산출물은 NEGO_DOCS/_archive_20260909_*/ 로 이동 (provenance 가 위치를 가리킨다) - 삭제: description.md, testdata/testset_100.json(파일럿 미사용), testdata/validate_dataset.py(미참조), ⑨ 본측정 폴더 내 중복 6개, 서버 로그 동결본 - .gitignore 에 재생성되는 중간 산출물 등록 - provenance 8종을 정의·원천·명령·결과 중심으로 재작성 (364줄 → 240줄) - 재현 검증: ⑦⑧② 집계기 재실행 시 동일 수치 자체측정 8종 전부 PASS — ① 85.67% ② 76.29% ③ 5.877% ⑥ p95 31.65ms ⑦ 10,272건 ⑧ 96.1% ⑨ 99.71% ⑩ 98.23% Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
146 lines
6.4 KiB
Python
146 lines
6.4 KiB
Python
#!/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/ 에 보관)
|
||
출력: 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()
|