Upload src/evaluate.py with huggingface_hub
Browse files- src/evaluate.py +121 -0
src/evaluate.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Test seti degerlendirmesi + threshold analizi.
|
| 3 |
+
- 30 soru (20 pozitif / 10 negatif) iki modelle aranir
|
| 4 |
+
- F1'i maksimize eden esik 200-nokta sweep ile bulunur
|
| 5 |
+
- Confusion matrix, Recall@k, MRR raporlanir
|
| 6 |
+
- Skor dagilimi + F1 egrisi grafikleri reports/ altina yazilir
|
| 7 |
+
|
| 8 |
+
Calistirma: python -m src.evaluate --config config.yaml
|
| 9 |
+
"""
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import chromadb
|
| 15 |
+
import matplotlib
|
| 16 |
+
matplotlib.use("Agg")
|
| 17 |
+
import matplotlib.pyplot as plt
|
| 18 |
+
import numpy as np
|
| 19 |
+
import pandas as pd
|
| 20 |
+
from sentence_transformers import SentenceTransformer
|
| 21 |
+
|
| 22 |
+
# Sorgu tarafi prompt ayarlari (dokuman tarafi embed_index.py'de)
|
| 23 |
+
MODELS = {
|
| 24 |
+
"magibu": ("magibu/embeddingmagibu-200m", "query", lambda t: t),
|
| 25 |
+
"e5": ("ytu-ce-cosmos/turkish-e5-large", None, lambda t: f"query: {t}"),
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
ABSTAIN_MESSAGE = "Bu sorunun cevabi dokumanlarimda yer almamaktadir."
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def evaluate_model(key, model_name, prompt_name, prefix_fn, test_set, client, root):
|
| 32 |
+
model = SentenceTransformer(model_name, trust_remote_code=True)
|
| 33 |
+
col = client.get_collection(f"chunks_{key}")
|
| 34 |
+
|
| 35 |
+
def embed(text):
|
| 36 |
+
kw = {"prompt_name": prompt_name} if prompt_name else {}
|
| 37 |
+
return model.encode(prefix_fn(text), normalize_embeddings=True, **kw).tolist()
|
| 38 |
+
|
| 39 |
+
rows = []
|
| 40 |
+
for q in test_set:
|
| 41 |
+
res = col.query(query_embeddings=[embed(q["question"])], n_results=5)
|
| 42 |
+
top_ids = res["ids"][0]
|
| 43 |
+
top_sims = [1 - d for d in res["distances"][0]] # cosine distance -> similarity
|
| 44 |
+
gt = q["ground_truth_chunk"]
|
| 45 |
+
hit_rank = top_ids.index(gt) + 1 if gt and gt in top_ids else None
|
| 46 |
+
rows.append({"id": q["id"], "label": q["label"],
|
| 47 |
+
"top1_sim": top_sims[0], "hit_rank": hit_rank})
|
| 48 |
+
df = pd.DataFrame(rows)
|
| 49 |
+
|
| 50 |
+
pos = df[df.label == "positive"]["top1_sim"].values
|
| 51 |
+
neg = df[df.label == "negative"]["top1_sim"].values
|
| 52 |
+
|
| 53 |
+
# F1 sweep: esik gozle degil, veri-gudumlu secilir
|
| 54 |
+
best_t, best_f1, f1_curve = 0.0, 0.0, []
|
| 55 |
+
thresholds = np.linspace(0, 1, 200)
|
| 56 |
+
for t in thresholds:
|
| 57 |
+
tp, fp = int((pos >= t).sum()), int((neg >= t).sum())
|
| 58 |
+
fn = int((pos < t).sum())
|
| 59 |
+
prec = tp / (tp + fp) if tp + fp else 0.0
|
| 60 |
+
rec = tp / (tp + fn) if tp + fn else 0.0
|
| 61 |
+
f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0
|
| 62 |
+
f1_curve.append(f1)
|
| 63 |
+
if f1 > best_f1:
|
| 64 |
+
best_f1, best_t = f1, t
|
| 65 |
+
|
| 66 |
+
tp, fp = int((pos >= best_t).sum()), int((neg >= best_t).sum())
|
| 67 |
+
fn, tn = int((pos < best_t).sum()), int((neg < best_t).sum())
|
| 68 |
+
pos_df = df[df.label == "positive"]
|
| 69 |
+
mrr = pos_df["hit_rank"].map(lambda r: 1 / r if pd.notna(r) else 0).mean()
|
| 70 |
+
|
| 71 |
+
# Grafik: skor dagilimi + F1 egrisi
|
| 72 |
+
fig, axes = plt.subplots(1, 2, figsize=(13, 4))
|
| 73 |
+
axes[0].hist(pos, bins=12, alpha=0.7, color="#2ecc71", label="Pozitif")
|
| 74 |
+
axes[0].hist(neg, bins=8, alpha=0.7, color="#e74c3c", label="Negatif")
|
| 75 |
+
axes[0].set_xlabel("Cosine Benzerlik"); axes[0].legend()
|
| 76 |
+
axes[0].set_title(f"{key} - Skor Dagilimi")
|
| 77 |
+
axes[1].plot(thresholds, f1_curve, color="#3498db")
|
| 78 |
+
axes[1].axvline(best_t, color="red", linestyle="--",
|
| 79 |
+
label=f"t={best_t:.3f} (F1={best_f1:.3f})")
|
| 80 |
+
axes[1].set_xlabel("Threshold"); axes[1].set_ylabel("F1"); axes[1].legend()
|
| 81 |
+
axes[1].set_title(f"{key} - F1 Sweep")
|
| 82 |
+
plt.tight_layout()
|
| 83 |
+
plt.savefig(root / f"reports/threshold_{key}.png", dpi=120)
|
| 84 |
+
plt.close()
|
| 85 |
+
|
| 86 |
+
return {
|
| 87 |
+
"threshold": round(best_t, 3), "f1": round(best_f1, 3),
|
| 88 |
+
"precision": round(tp / (tp + fp), 3) if tp + fp else 0,
|
| 89 |
+
"recall": round(tp / (tp + fn), 3) if tp + fn else 0,
|
| 90 |
+
"tp": tp, "fp": fp, "fn": fn, "tn": tn,
|
| 91 |
+
"recall_at_1": round((pos_df.hit_rank == 1).sum() / len(pos_df), 3),
|
| 92 |
+
"recall_at_3": round((pos_df.hit_rank <= 3).sum() / len(pos_df), 3),
|
| 93 |
+
"recall_at_5": round((pos_df.hit_rank <= 5).sum() / len(pos_df), 3),
|
| 94 |
+
"mrr": round(mrr, 3),
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def run(config_path: str = "config.yaml") -> None:
|
| 99 |
+
root = Path(config_path).resolve().parent
|
| 100 |
+
with open(root / "data/test_set.jsonl", encoding="utf-8") as f:
|
| 101 |
+
test_set = [json.loads(l) for l in f]
|
| 102 |
+
client = chromadb.PersistentClient(path=str(root / "data/chroma"))
|
| 103 |
+
(root / "reports").mkdir(exist_ok=True)
|
| 104 |
+
|
| 105 |
+
results = {}
|
| 106 |
+
for key, (name, prompt, prefix) in MODELS.items():
|
| 107 |
+
print(f"\n=== {key} ===")
|
| 108 |
+
results[key] = evaluate_model(key, name, prompt, prefix,
|
| 109 |
+
test_set, client, root)
|
| 110 |
+
for m, v in results[key].items():
|
| 111 |
+
print(f" {m}: {v}")
|
| 112 |
+
|
| 113 |
+
with open(root / "data/eval_results.json", "w", encoding="utf-8") as f:
|
| 114 |
+
json.dump(results, f, ensure_ascii=False, indent=2)
|
| 115 |
+
print("\n[OK] data/eval_results.json + reports/threshold_*.png")
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
if __name__ == "__main__":
|
| 119 |
+
ap = argparse.ArgumentParser()
|
| 120 |
+
ap.add_argument("--config", default="config.yaml")
|
| 121 |
+
run(ap.parse_args().config)
|