초기 커밋 — 협상 AI 에이전트 정본: 엔진·데모 콘솔·측정 인프라·증빙
- server/: FastAPI 협상 엔진 (5라운드, Q-Table/UCB, 페르소나 계측, :53117) - frontend/: 데모 콘솔 (React+Tailwind → nginx, /api 프록시) - eval/·testdata/: 지표 8종 측정 하네스 + 재현 가능 테스트셋 - results/: 측정 증빙 (지표별 result+provenance, raw 원본 동결+SHA256) ① 86.0 · ② 76.0 · ③ 5.99% · ⑥ p95 3.61ms · ⑦ 611만/년 · ⑧ 91/100 · ⑨ 99.71 · ⑩ 97.99 - docker-compose.yml + run.sh: backend+frontend 일괄 기동 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0112XUWF4bc3gGrEt8vsYCzy
This commit is contained in:
commit
dfb9ad6e66
268 files changed
+164241
No files matched your search
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""⑨ 품목별 협상 시나리오 분류 — 자체 라벨링 데이터 구축.
|
||||
|
||||
계획서: "자체 구축한 라벨링 데이터(품목 - 협상 시나리오)에 대한 Classification 결과의 F1-score"
|
||||
|
||||
구축 방식 (2026-08-28 확정, B안):
|
||||
- 품목명: 운용 견적명에서 분리·정제한 실상품명 목록(testdata/product_names.json) 재사용
|
||||
- 라벨: 4분면 룰(testdata/scenario_rule.py — 원본 nego_quadrant_service 중립 재현)로
|
||||
(협상구분, 공급유형, 공급사수, 매출)에서 산출 → Scenario_A/B/C/D
|
||||
- 피처: 품목명 + 협상구분·공급유형·공급사수·매출·품목가격 (실서비스 판정 입력과 동일 계열)
|
||||
- 분할: **품목명 단위 8:2 홀드아웃** (같은 품목이 train/test에 걸치지 않음 — 누수 방지)
|
||||
|
||||
사용: python build_dataset.py [--per-name 6] [--seed 926]
|
||||
출력: data/train.csv, data/test.csv
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import random
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
TESTDATA = HERE.parent.parent / "testdata"
|
||||
sys.path.insert(0, str(TESTDATA))
|
||||
|
||||
from scenario_rule import scenario_label # noqa: E402
|
||||
|
||||
|
||||
def log_uniform(rng, lo, hi):
|
||||
import math
|
||||
return math.exp(rng.uniform(math.log(lo), math.log(hi)))
|
||||
|
||||
|
||||
def sample_features(rng: random.Random) -> dict:
|
||||
rq_type = rng.choice(["재협상", "재협상", "재견적"]) # 운용 비중(재협상 2:1 근사)
|
||||
dist = rng.choice(["R", "W", "M"])
|
||||
partners = rng.choice([0, 1, 2, 3, 4, 5])
|
||||
revenue = int(log_uniform(rng, 1_000_000, 100_000_000))
|
||||
item_price = round(log_uniform(rng, 1_000, 2_000_000) / 10) * 10
|
||||
return {"rq_type": rq_type, "dist": dist, "partners": partners,
|
||||
"revenue": revenue, "item_price": item_price}
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--per-name", type=int, default=6, help="품목명당 표본 수")
|
||||
ap.add_argument("--seed", type=int, default=926)
|
||||
ap.add_argument("--test-ratio", type=float, default=0.2)
|
||||
args = ap.parse_args()
|
||||
|
||||
rng = random.Random(args.seed)
|
||||
names = json.load(open(TESTDATA / "product_names.json", encoding="utf-8"))["names"]
|
||||
rng.shuffle(names)
|
||||
|
||||
# 품목명 단위 분할 (누수 방지)
|
||||
n_test = int(len(names) * args.test_ratio)
|
||||
test_names = set(names[:n_test])
|
||||
|
||||
(HERE / "data").mkdir(exist_ok=True)
|
||||
fields = ["item_name", "rq_type", "dist", "partners", "revenue", "item_price", "scenario"]
|
||||
counts = {"train": 0, "test": 0}
|
||||
label_dist = {}
|
||||
with open(HERE / "data" / "train.csv", "w", encoding="utf-8-sig", newline="") as ftr, \
|
||||
open(HERE / "data" / "test.csv", "w", encoding="utf-8-sig", newline="") as fte:
|
||||
wtr, wte = csv.DictWriter(ftr, fields), csv.DictWriter(fte, fields)
|
||||
wtr.writeheader(), wte.writeheader()
|
||||
for name in names:
|
||||
for _ in range(args.per_name):
|
||||
feat = sample_features(rng)
|
||||
label = scenario_label(feat["rq_type"], feat["dist"],
|
||||
feat["partners"], feat["revenue"])
|
||||
row = {"item_name": name, **feat, "scenario": label}
|
||||
label_dist[label] = label_dist.get(label, 0) + 1
|
||||
if name in test_names:
|
||||
wte.writerow(row); counts["test"] += 1
|
||||
else:
|
||||
wtr.writerow(row); counts["train"] += 1
|
||||
|
||||
print(json.dumps({"품목명": len(names), "train": counts["train"], "test": counts["test"],
|
||||
"라벨분포": label_dist, "seed": args.seed}, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
"""⑨ 품목별 협상 시나리오 분류 — 독립 실행 채점기 (표준 라이브러리만).
|
||||
|
||||
입력: data/predictions.csv — 헤더 y_true,y_pred (분류기 test set 예측 결과)
|
||||
사용: python run.py [--input data/predictions.csv] [--target 96]
|
||||
산식: macro-F1 (클래스별 F1 단순 평균) — micro-F1(=accuracy) 병기
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--input", default=str(HERE / "data" / "predictions.csv"))
|
||||
ap.add_argument("--target", type=float, default=96.0)
|
||||
args = ap.parse_args()
|
||||
|
||||
with open(args.input, encoding="utf-8-sig") as f:
|
||||
rows = list(csv.DictReader(f))
|
||||
y_true = [r["y_true"].strip() for r in rows]
|
||||
y_pred = [r["y_pred"].strip() for r in rows]
|
||||
|
||||
tp, fp, fn = defaultdict(int), defaultdict(int), defaultdict(int)
|
||||
with open(HERE / "detail.jsonl", "w", encoding="utf-8") as df:
|
||||
for i, (t, p) in enumerate(zip(y_true, y_pred)):
|
||||
if t == p:
|
||||
tp[t] += 1
|
||||
else:
|
||||
fp[p] += 1
|
||||
fn[t] += 1
|
||||
df.write(json.dumps({"i": i, "y_true": t, "y_pred": p, "정답": t == p},
|
||||
ensure_ascii=False) + "\n")
|
||||
|
||||
per_class, f1s = {}, []
|
||||
for c in sorted(set(y_true) | set(y_pred)):
|
||||
prec = tp[c] / (tp[c] + fp[c]) if tp[c] + fp[c] else 0.0
|
||||
rec = tp[c] / (tp[c] + fn[c]) if tp[c] + fn[c] else 0.0
|
||||
f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0
|
||||
per_class[c] = {"precision": round(prec, 4), "recall": round(rec, 4),
|
||||
"f1": round(f1, 4), "support": y_true.count(c)}
|
||||
f1s.append(f1)
|
||||
|
||||
macro_f1 = round(100 * sum(f1s) / len(f1s), 2) if f1s else 0.0
|
||||
micro_f1 = round(100 * sum(1 for t, p in zip(y_true, y_pred) if t == p) / len(y_true), 2) \
|
||||
if y_true else 0.0
|
||||
|
||||
out = {
|
||||
"n": len(y_true),
|
||||
"산식": "macro-F1 (클래스별 F1 단순 평균) — 불균형 대비 보수적 채점",
|
||||
"macro_f1_pct": macro_f1,
|
||||
"micro_f1_pct(accuracy)": micro_f1,
|
||||
"클래스별": per_class,
|
||||
"target_pct": args.target,
|
||||
"verdict": "PASS" if macro_f1 >= args.target else "FAIL",
|
||||
}
|
||||
(HERE / "result.json").write_text(json.dumps(out, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8")
|
||||
print(json.dumps(out, ensure_ascii=False, indent=1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,142 @@
|
||||
#!/usr/bin/env python3
|
||||
"""⑨ 시나리오 분류기 — Pytorch 학습·추론 (평가환경 명시 프레임워크).
|
||||
|
||||
모델: 품목명 문자 임베딩(mean-pool) + 구조 피처 → MLP → 4클래스
|
||||
- 문자 임베딩 32차원, 은닉 64, CrossEntropy, Adam
|
||||
- 시드 고정(재현성), CPU 학습 (수 초 내 수렴)
|
||||
|
||||
사용: python train.py [--epochs 12] [--seed 926]
|
||||
출력: data/predictions.csv (y_true,y_pred — 채점기 run.py 입력), model.pt
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
CLASSES = ["Scenario_A", "Scenario_B", "Scenario_C", "Scenario_D"]
|
||||
DISTS = {"R": 0, "W": 1, "M": 2}
|
||||
RQ_TYPES = {"재협상": 0, "재견적": 1}
|
||||
MAX_NAME_LEN = 40
|
||||
|
||||
|
||||
def load_rows(path):
|
||||
with open(path, encoding="utf-8-sig") as f:
|
||||
return list(csv.DictReader(f))
|
||||
|
||||
|
||||
def build_vocab(rows):
|
||||
chars = set()
|
||||
for r in rows:
|
||||
chars.update(r["item_name"][:MAX_NAME_LEN])
|
||||
vocab = {c: i + 2 for i, c in enumerate(sorted(chars))} # 0=pad, 1=unk
|
||||
return vocab
|
||||
|
||||
|
||||
def encode(rows, vocab):
|
||||
xs_name, xs_feat, ys = [], [], []
|
||||
for r in rows:
|
||||
name = r["item_name"][:MAX_NAME_LEN]
|
||||
ids = [vocab.get(c, 1) for c in name] + [0] * (MAX_NAME_LEN - len(name))
|
||||
xs_name.append(ids)
|
||||
dist_onehot = [0.0, 0.0, 0.0]
|
||||
dist_onehot[DISTS[r["dist"]]] = 1.0
|
||||
rq_onehot = [0.0, 0.0]
|
||||
rq_onehot[RQ_TYPES[r["rq_type"]]] = 1.0
|
||||
# 매출구간: 엔진 상태계(RevenueRange)와 동일한 이산화 — ≤1,000만 / ≤3,000만 / 초과
|
||||
rev = float(r["revenue"])
|
||||
rev_band = [0.0, 0.0, 0.0]
|
||||
rev_band[0 if rev <= 10_000_000 else (1 if rev <= 30_000_000 else 2)] = 1.0
|
||||
xs_feat.append([
|
||||
math.log10(rev),
|
||||
math.log10(float(r["item_price"])),
|
||||
float(r["partners"]) / 5.0,
|
||||
*rev_band, *dist_onehot, *rq_onehot,
|
||||
])
|
||||
ys.append(CLASSES.index(r["scenario"]))
|
||||
return (torch.tensor(xs_name, dtype=torch.long),
|
||||
torch.tensor(xs_feat, dtype=torch.float32),
|
||||
torch.tensor(ys, dtype=torch.long))
|
||||
|
||||
|
||||
class ScenarioClassifier(nn.Module):
|
||||
def __init__(self, vocab_size, n_feat, emb_dim=32, hidden=64):
|
||||
super().__init__()
|
||||
self.emb = nn.Embedding(vocab_size, emb_dim, padding_idx=0)
|
||||
self.mlp = nn.Sequential(
|
||||
nn.Linear(emb_dim + n_feat, hidden), nn.ReLU(),
|
||||
nn.Linear(hidden, hidden), nn.ReLU(),
|
||||
nn.Linear(hidden, len(CLASSES)),
|
||||
)
|
||||
|
||||
def forward(self, name_ids, feats):
|
||||
mask = (name_ids != 0).unsqueeze(-1).float()
|
||||
emb = (self.emb(name_ids) * mask).sum(1) / mask.sum(1).clamp(min=1.0)
|
||||
return self.mlp(torch.cat([emb, feats], dim=1))
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--epochs", type=int, default=12)
|
||||
ap.add_argument("--batch", type=int, default=128)
|
||||
ap.add_argument("--lr", type=float, default=1e-3)
|
||||
ap.add_argument("--seed", type=int, default=926)
|
||||
args = ap.parse_args()
|
||||
|
||||
random.seed(args.seed)
|
||||
torch.manual_seed(args.seed)
|
||||
|
||||
train_rows = load_rows(HERE / "data" / "train.csv")
|
||||
test_rows = load_rows(HERE / "data" / "test.csv")
|
||||
vocab = build_vocab(train_rows)
|
||||
|
||||
tr_name, tr_feat, tr_y = encode(train_rows, vocab)
|
||||
te_name, te_feat, te_y = encode(test_rows, vocab)
|
||||
|
||||
model = ScenarioClassifier(vocab_size=len(vocab) + 2, n_feat=tr_feat.shape[1])
|
||||
opt = torch.optim.Adam(model.parameters(), lr=args.lr)
|
||||
loss_fn = nn.CrossEntropyLoss()
|
||||
|
||||
n = len(tr_y)
|
||||
for epoch in range(args.epochs):
|
||||
model.train()
|
||||
perm = torch.randperm(n)
|
||||
total = 0.0
|
||||
for i in range(0, n, args.batch):
|
||||
idx = perm[i:i + args.batch]
|
||||
opt.zero_grad()
|
||||
out = model(tr_name[idx], tr_feat[idx])
|
||||
loss = loss_fn(out, tr_y[idx])
|
||||
loss.backward()
|
||||
opt.step()
|
||||
total += loss.item() * len(idx)
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
acc = (model(te_name, te_feat).argmax(1) == te_y).float().mean().item()
|
||||
print(f"epoch {epoch + 1:2d} loss {total / n:.4f} test_acc {acc:.4f}", flush=True)
|
||||
|
||||
# 추론 → 채점기 입력(predictions.csv) 저장
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
preds = model(te_name, te_feat).argmax(1).tolist()
|
||||
with open(HERE / "data" / "predictions.csv", "w", encoding="utf-8-sig", newline="") as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(["y_true", "y_pred"])
|
||||
for t, p in zip(te_y.tolist(), preds):
|
||||
w.writerow([CLASSES[t], CLASSES[p]])
|
||||
|
||||
torch.save({"state_dict": model.state_dict(), "vocab": vocab,
|
||||
"classes": CLASSES, "seed": args.seed}, HERE / "model.pt")
|
||||
print(json.dumps({"train": len(train_rows), "test": len(test_rows),
|
||||
"vocab": len(vocab), "torch": torch.__version__,
|
||||
"출력": "data/predictions.csv, model.pt"}, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user