File size: 6,942 Bytes
ab773bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
"""
Benchmark / Threshold Analizi
-----------------------------------
30 test sorusunu (eval/test_questions.json) çalıştırır:
  - Her soru için embed edilir, ChromaDB'de en yakın chunk aranır, top-1 skor kaydedilir.
  - Farklı threshold değerleri için confusion matrix hesaplanır:
        Pozitif soru + skor >= threshold  -> TP (doğru yanıtlandı)
        Pozitif soru + skor <  threshold  -> FN (yanlışlıkla reddedildi)
        Negatif soru + skor <  threshold  -> TN (doğru reddedildi)
        Negatif soru + skor >= threshold  -> FP (yanlışlıkla yanıtlandı / halüsinasyon riski)
  - En iyi accuracy/F1'i veren threshold önerilir.
  - Ayrıca pozitif sorularda, dönen chunk'ın url'i beklenen url ile eşleşiyor mu
    (retrieval doğruluğu) kontrol edilir.

Çalıştırma:
    EMBEDDING_BACKEND=mock python eval/run_eval.py
"""
import sys
import os
import json

sys.path.append(os.path.join(os.path.dirname(__file__), ".."))

from src import config
from src.vector_store import VectorStore
from src.embedder import get_embedder

THRESHOLD_SWEEP = [round(x * 0.05, 2) for x in range(1, 20)]  # 0.05, 0.10, ..., 0.95


def load_questions():
    path = os.path.join(os.path.dirname(__file__), "test_questions.json")
    with open(path, encoding="utf-8") as f:
        data = json.load(f)
    return data["questions"]


def run_raw_search(questions, store, embedder, top_k=None):
    """Her soru için (threshold uygulamadan) top-1 skoru ve retrieval bilgisini toplar."""
    results = []
    for q in questions:
        query_vector = embedder.embed([q["question"]])[0]
        hits = store.query(query_vector, top_k=top_k or config.TOP_K)
        top = hits[0] if hits else {"score": 0.0, "url": None, "chunk_text": ""}
        results.append({
            "id": q["id"],
            "type": q["type"],
            "question": q["question"],
            "expected_source_url": q.get("expected_source_url"),
            "top_score": top["score"],
            "top_url": top.get("url"),
            "top_chunk_preview": top.get("chunk_text", "")[:80],
        })
    return results


def confusion_matrix_at_threshold(results, threshold):
    tp = fn = tn = fp = 0
    for r in results:
        answered = r["top_score"] >= threshold
        if r["type"] == "positive":
            if answered:
                tp += 1
            else:
                fn += 1
        else:  # negative
            if answered:
                fp += 1
            else:
                tn += 1
    total = tp + fn + tn + fp
    accuracy = (tp + tn) / total if total else 0.0
    precision = tp / (tp + fp) if (tp + fp) else 0.0
    recall = tp / (tp + fn) if (tp + fn) else 0.0
    f1 = 2 * precision * recall / (precision + recall) if (precision + recall) else 0.0
    return {"threshold": threshold, "tp": tp, "fn": fn, "tn": tn, "fp": fp,
            "accuracy": accuracy, "precision": precision, "recall": recall, "f1": f1}


def sweep_thresholds(results):
    return [confusion_matrix_at_threshold(results, t) for t in THRESHOLD_SWEEP]


def retrieval_accuracy(results):
    """Pozitif sorularda, en yüksek skorlu chunk'ın url'i beklenen url ile eşleşiyor mu?"""
    positives = [r for r in results if r["type"] == "positive"]
    correct = sum(1 for r in positives if r["top_url"] == r["expected_source_url"])
    return correct, len(positives)


def main():
    print(f"Backend: {config.EMBEDDING_BACKEND} | Chroma: {config.CHROMA_PERSIST_DIR}\n")

    questions = load_questions()
    store = VectorStore()
    embedder = get_embedder()

    print(f"Toplam {len(questions)} soru çalıştırılıyor "
          f"({sum(1 for q in questions if q['type']=='positive')} pozitif, "
          f"{sum(1 for q in questions if q['type']=='negative')} negatif)...\n")

    results = run_raw_search(questions, store, embedder)

    # --- Ham sonuçlar ---
    print(f"{'ID':5} {'Tip':9} {'Skor':7} {'Doğru URL mü?':14} Soru")
    print("-" * 100)
    for r in results:
        url_match = ""
        if r["type"] == "positive":
            url_match = "EVET" if r["top_url"] == r["expected_source_url"] else "HAYIR"
        print(f"{r['id']:5} {r['type']:9} {r['top_score']:.3f}   {url_match:14} {r['question'][:60]}")

    correct, total_pos = retrieval_accuracy(results)
    print(f"\nRetrieval doğruluğu (pozitif sorularda doğru kaynağı bulma): {correct}/{total_pos}")

    # --- Threshold sweep ---
    print("\n" + "=" * 70)
    print("THRESHOLD SWEEP")
    print("=" * 70)
    print(f"{'Thr':6} {'TP':4} {'FN':4} {'TN':4} {'FP':4} {'Acc':6} {'Prec':6} {'Rec':6} {'F1':6}")
    sweep = sweep_thresholds(results)
    for s in sweep:
        print(f"{s['threshold']:.2f}   {s['tp']:4} {s['fn']:4} {s['tn']:4} {s['fp']:4} "
              f"{s['accuracy']:.3f}  {s['precision']:.3f}  {s['recall']:.3f}  {s['f1']:.3f}")

    best = max(sweep, key=lambda s: (s["f1"], s["accuracy"]))
    print(f"\n>>> Önerilen threshold (en iyi F1): {best['threshold']} "
          f"(accuracy={best['accuracy']:.3f}, precision={best['precision']:.3f}, recall={best['recall']:.3f})")

    write_report(results, sweep, best, correct, total_pos)


def write_report(results, sweep, best, correct, total_pos):
    path = os.path.join(os.path.dirname(__file__), "eval_results.md")
    lines = [
        "# Eşik (Threshold) Analizi Sonuçları",
        "",
        f"- Embedding backend: `{config.EMBEDDING_BACKEND}`",
        f"- Toplam soru: {len(results)} "
        f"({sum(1 for r in results if r['type']=='positive')} pozitif, "
        f"{sum(1 for r in results if r['type']=='negative')} negatif)",
        f"- Retrieval doğruluğu (pozitif sorularda doğru url): {correct}/{total_pos}",
        f"- **Önerilen threshold: {best['threshold']}** "
        f"(F1={best['f1']:.3f}, accuracy={best['accuracy']:.3f}, "
        f"precision={best['precision']:.3f}, recall={best['recall']:.3f})",
        "",
        "## Threshold Sweep Tablosu",
        "",
        "| Threshold | TP | FN | TN | FP | Accuracy | Precision | Recall | F1 |",
        "|---|---|---|---|---|---|---|---|---|",
    ]
    for s in sweep:
        lines.append(
            f"| {s['threshold']:.2f} | {s['tp']} | {s['fn']} | {s['tn']} | {s['fp']} | "
            f"{s['accuracy']:.3f} | {s['precision']:.3f} | {s['recall']:.3f} | {s['f1']:.3f} |"
        )

    lines += ["", "## Soru Bazlı Ham Sonuçlar", "",
              "| ID | Tip | Top Score | Top URL Doğru mu | Soru |",
              "|---|---|---|---|---|"]
    for r in results:
        url_match = "-"
        if r["type"] == "positive":
            url_match = "EVET" if r["top_url"] == r["expected_source_url"] else "HAYIR"
        lines.append(f"| {r['id']} | {r['type']} | {r['top_score']:.3f} | {url_match} | {r['question']} |")

    with open(path, "w", encoding="utf-8") as f:
        f.write("\n".join(lines))
    print(f"\nRapor yazıldı: {path}")


if __name__ == "__main__":
    main()