forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rule_based_chatbot

Clone
★ 0

0 watching0 forksPython1.2 MiBdaf5582Kadir Yönak3 months ago37 commits

evaluate.py181 lines, 6.8 KiBHistoryRawDownload
1"""Tam değerlendirme koşum aracı (Aşama 10).
2
3Benchmark'ı izlenmiş boru hattından geçirir ve tek bir raporda toplar:
4- macro-F1 (başlık), accuracy, per-class P/R/F1
5- coverage, accuracy-on-covered, false-fallback
6- OOS recall
7- must_not_match çift-karışma raporu
8- top-1 vs top-3 accuracy
9- latency p50/p95
10
11Çıktı hem makine-okunur (dict) hem insan-okunur (format_report) — regresyon için
12Aşama 14, ayar için Aşama 11 bunu kullanır.
13"""
14
15from __future__ import annotations
16
17from typing import Any
18
19from .benchmark import OOS_LABEL, load_benchmark
20from ..catalog import INTENTS
21from ..decision import DEFAULT_THRESHOLD, _is_confusable_pair
22from .metrics import (
23 accuracy,
24 macro_f1,
25 per_class_scores,
26 percentile,
27 topk_accuracy,
28)
29from ..observability import process
30from ..similarity import SimilarityMatcher, get_default_matcher
31
32# in-scope iken FALLBACK'e düşeni işaretlemek için sözde etiket.
33_FALLBACK_LABEL = "__fallback__"
34
35
36def run_evaluation(
37 threshold: float = DEFAULT_THRESHOLD,
38 matcher: SimilarityMatcher | None = None,
39 records: list[dict[str, Any]] | None = None,
40) -> dict[str, Any]:
41 """Benchmark üzerinde tam değerlendirme yapar ve metrik sözlüğü döndürür."""
42
43 matcher = matcher or get_default_matcher()
44 records = records if records is not None else load_benchmark()
45 labels = {i["intent"] for i in INTENTS}
46
47 in_pairs: list[tuple[str, str]] = [] # (true, pred|__fallback__)
48 covered_pairs: list[tuple[str, str]] = [] # yalnızca kapsananlar
49 topk_records: list[tuple[str, list[str]]] = [] # (true, sıralı tahminler)
50 latencies: list[float] = []
51
52 covered = correct = false_fallback = 0
53 oos_total = oos_caught = 0
54 confusable_wrong = nonconfusable_wrong = 0
55 wrong_pairs: list[tuple[str, str]] = []
56
57 for r in records:
58 role = r.get("role", "ziyaretci")
59 authenticated = role != "ziyaretci"
60 _, trace = process(
61 r["question"], role=role, authenticated=authenticated, matcher=matcher
62 )
63 # Eşik parametresini uygulamak için kararı yeniden değerlendirmek yerine,
64 # process varsayılan eşiği kullanır; ayar taraması için threshold enjekte edelim.
65 # (threshold != default ise skorlardan yeniden karar ver.)
66 pred = _reconsider(trace, threshold)
67 latencies.append(trace["latency_ms"]["total"])
68
69 expected = r["expected_intent"]
70 if expected == OOS_LABEL:
71 oos_total += 1
72 if pred is None:
73 oos_caught += 1
74 continue
75
76 # in-scope
77 ranked_intents = _ranked_intents(trace)
78 topk_records.append((expected, ranked_intents))
79
80 if pred is None:
81 false_fallback += 1
82 in_pairs.append((expected, _FALLBACK_LABEL))
83 else:
84 covered += 1
85 in_pairs.append((expected, pred))
86 covered_pairs.append((expected, pred))
87 if pred == expected:
88 correct += 1
89 else:
90 wrong_pairs.append((expected, pred))
91 if _is_confusable_pair(expected, pred):
92 confusable_wrong += 1
93 else:
94 nonconfusable_wrong += 1
95
96 in_scope_total = len(in_pairs)
97 report: dict[str, Any] = {
98 "threshold": threshold,
99 "in_scope_total": in_scope_total,
100 "oos_total": oos_total,
101 "macro_f1": macro_f1(in_pairs, labels),
102 "accuracy": accuracy(in_pairs),
103 "coverage": covered / in_scope_total if in_scope_total else 0.0,
104 "accuracy_on_covered": correct / covered if covered else 0.0,
105 "false_fallback": false_fallback,
106 "oos_recall": oos_caught / oos_total if oos_total else 0.0,
107 "top1_accuracy": topk_accuracy(topk_records, 1),
108 "top3_accuracy": topk_accuracy(topk_records, 3),
109 "confusable_wrong": confusable_wrong,
110 "nonconfusable_wrong": nonconfusable_wrong,
111 "wrong_pairs": wrong_pairs,
112 "latency_p50_ms": percentile(latencies, 50),
113 "latency_p95_ms": percentile(latencies, 95),
114 "per_class": per_class_scores(covered_pairs, labels),
115 }
116 return report
117
118
119def _ranked_intents(trace: dict[str, Any]) -> list[str]:
120 """Trace'ten sıralı tahmin listesi (kural yolu -> tek eleman)."""
121
122 if trace["rule_layer"]["hit"]:
123 return [trace["rule_layer"]["intent"]]
124 return [item["intent"] for item in trace["similarity"]["top_k"]]
125
126
127def _reconsider(trace: dict[str, Any], threshold: float) -> str | None:
128 """Verilen eşiğe göre tahmini belirler (kural her zaman kazanır; alan kapısı uygulanır)."""
129
130 if trace["rule_layer"]["hit"]:
131 return trace["rule_layer"]["intent"]
132 if not trace["similarity"].get("in_domain", True):
133 return None
134 top_k = trace["similarity"]["top_k"]
135 if not top_k:
136 return None
137 top = top_k[0]
138 if top["score"] < threshold:
139 return None
140 return top["intent"]
141
142
143def format_report(report: dict[str, Any]) -> str:
144 """İnsan-okunur özet."""
145
146 lines = [
147 "================ DEĞERLENDİRME RAPORU ================",
148 f"Eşik (threshold) : {report['threshold']:.3f}",
149 f"In-scope / OOS : {report['in_scope_total']} / {report['oos_total']}",
150 "--- Genel ---",
151 f"Macro-F1 (BAŞLIK) : {report['macro_f1']:.3f}",
152 f"Accuracy : {report['accuracy']:.1%}",
153 f"Top-1 / Top-3 acc : {report['top1_accuracy']:.1%} / {report['top3_accuracy']:.1%}",
154 "--- Abstention (eşik) ---",
155 f"Coverage : {report['coverage']:.1%}",
156 f"Accuracy-on-covered : {report['accuracy_on_covered']:.1%}",
157 f"False fallback : {report['false_fallback']}",
158 f"OOS recall : {report['oos_recall']:.1%}",
159 "--- must_not_match ---",
160 f"Karışan çift (confusable) yanlış : {report['confusable_wrong']}",
161 f"Diğer (beklenmedik) yanlış : {report['nonconfusable_wrong']}",
162 "--- Latency ---",
163 f"p50 / p95 (ms) : {report['latency_p50_ms']:.3f} / {report['latency_p95_ms']:.3f}",
164 "--- En zayıf 8 intent (F1, kapsananlarda) ---",
165 ]
166 worst = sorted(report["per_class"], key=lambda s: (s.f1, -s.support))
167 for s in worst[:8]:
168 lines.append(
169 f" {s.label:26s} P={s.precision:.2f} R={s.recall:.2f} F1={s.f1:.2f} (n={s.support})"
170 )
171 if report["wrong_pairs"]:
172 lines.append("--- Yanlış tahminler (beklenen -> bulunan) ---")
173 for true, pred in report["wrong_pairs"]:
174 mark = "~" if _is_confusable_pair(true, pred) else "x"
175 lines.append(f" [{mark}] {true} -> {pred}")
176 lines.append("=====================================================")
177 return "\n".join(lines)
178
179
180if __name__ == "__main__":
181 print(format_report(run_evaluation()))