File size: 5,049 Bytes
cf29045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""T-72 — Phân tích lỗi: 100 ca sai nặng nhất mỗi loại, kèm reason_code."""
from __future__ import annotations

import argparse
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any, Dict, List

from ..common.config import add_config_args, load_config
from ..common.io_utils import iter_jsonl
from ..common.logging_utils import get_logger

LOG = get_logger("error_analysis")


def render(groups: Dict[str, List[Dict[str, Any]]], counts: Dict[str, Counter],
           n_total: int, top: int) -> str:
    L = ["# Phân tích lỗi (T-72)", "", f"Tổng số mẫu đã chấm: **{n_total}**", "",
         "## 1. Thống kê lỗi theo loại", "", "| Loại lỗi | Số ca | Tỉ lệ |", "|---|---:|---:|"]
    for k, items in sorted(groups.items(), key=lambda x: -len(x[1])):
        L.append(f"| `{k}` | {len(items)} | {len(items)/max(1,n_total):.2%} |")

    L += ["", "## 2. Nhầm lẫn thường gặp nhất", ""]
    for head, c in counts.items():
        if not c:
            continue
        L += [f"### `{head}`", ""]
        for (g, p), n in c.most_common(10):
            L.append(f"- gold `{g}` → đoán `{p}`: **{n}** ca")
        L.append("")

    L += ["## 3. Ca sai cụ thể", ""]
    for k, items in sorted(groups.items(), key=lambda x: -len(x[1])):
        L += [f"### `{k}` — {min(top, len(items))}/{len(items)} ca đầu", ""]
        for it in items[:top]:
            L += [f"- **{it.get('doc_id')}** · conf={it.get('conf')} · "
                  f"reason=`{it.get('reason_code')}`",
                  f"  - gold: `{it.get('gold')}` → đoán: `{it.get('pred')}`",
                  f"  - text: {str(it.get('text', ''))[:200]}"]
        L.append("")
    L += ["## 4. Hướng khắc phục gợi ý", "",
          "- Nhầm lẫn tập trung ở một cặp nhãn ⇒ hai nhãn đó có thể chồng lấn về định nghĩa; "
          "cân nhắc gộp trong `configs/labels.yaml` hoặc siết luật trong `weak_rules.yaml`.",
          "- Lỗi tập trung ở mẫu có `conf` cao ⇒ nhãn huấn luyện bị nhiễu, xem "
          "`reports/label_agreement.md`.",
          "- `over_abstain` nhiều ⇒ hạ `tau_rerank` trong `configs/evidence_gate.yaml`; "
          "`under_abstain` nhiều ⇒ nâng lên (đo lại trên DEV, không đụng TEST).", ""]
    return "\n".join(L)


def main() -> None:
    ap = argparse.ArgumentParser(description="T-72 phân tích lỗi")
    ap.add_argument("--dump", required=True,
                    help="file jsonl sinh bởi eval_end_to_end.py --dump")
    ap.add_argument("--top", type=int, default=100)
    add_config_args(ap)
    args = ap.parse_args()
    cfg = load_config("paths", args.overrides)

    if not Path(args.dump).exists():
        raise SystemExit(f"Không có {args.dump}. Chạy: "
                         "python -m src.evaluation.eval_end_to_end --dump preds.jsonl")

    groups: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
    counts: Dict[str, Counter] = {"next_action": Counter(), "intent": Counter(),
                                  "domain": Counter()}
    rows = list(iter_jsonl(args.dump))
    for r in rows:
        for head, gold_key in (("next_action", "gold_action"), ("intent", "gold_intent"),
                               ("domain", "gold_domain")):
            g, p = r.get(gold_key), r.get(head)
            if g and p and g != p:
                counts[head][(g, p)] += 1
                groups[f"sai_{head}"].append({
                    "doc_id": r.get("doc_id"), "gold": g, "pred": p,
                    "conf": (r.get("confidence") or {}).get(
                        "action" if head == "next_action" else head),
                    "reason_code": r.get("reason_code"),
                    "text": r.get("answer", "")[:200]})
        if r.get("reason_code") and r.get("gold_action"):
            groups["tu_choi_tra_loi"].append({
                "doc_id": r.get("doc_id"), "gold": r.get("gold_action"),
                "pred": r.get("next_action"), "reason_code": r.get("reason_code"),
                "conf": None, "text": r.get("answer", "")[:200]})
        if (r.get("can_answer_directly")
                and r.get("next_action") in ("PROVIDE_LEGAL_BASIS", "PROVIDE_PROCEDURE_GUIDE")
                and not r.get("evidence")):
            groups["tra_loi_khong_bang_chung"].append({
                "doc_id": r.get("doc_id"), "gold": "phải có bằng chứng",
                "pred": "không có", "reason_code": r.get("reason_code"),
                "conf": None, "text": r.get("answer", "")[:200]})

    # Sai ở độ tự tin cao = nguy hiểm nhất -> xếp trước
    for k in groups:
        groups[k].sort(key=lambda x: -(x.get("conf") or 0))

    out = f"{cfg['reports']['dir']}/error_analysis.md"
    with open(out, "w", encoding="utf-8") as f:
        f.write(render(groups, counts, len(rows), args.top))
    LOG.info("-> %s | %s", out, {k: len(v) for k, v in groups.items()})


if __name__ == "__main__":
    main()