forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rule_based_chatbot

Clone
★ 0

0 watching0 forksPython1.2 MiBa039b60Ahmet Kaan Gümüş2 months ago64 commits

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