Datasets:
Create scorer.py
Browse files
scorer.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from typing import Dict, Any, List
|
| 3 |
+
import json
|
| 4 |
+
|
| 5 |
+
@dataclass
|
| 6 |
+
class ScoreResult:
|
| 7 |
+
score: float
|
| 8 |
+
details: Dict[str, Any]
|
| 9 |
+
|
| 10 |
+
BANDS = {"low", "medium", "high"}
|
| 11 |
+
|
| 12 |
+
def score(sample: Dict[str, Any], prediction: str) -> ScoreResult:
|
| 13 |
+
try:
|
| 14 |
+
pred = json.loads(prediction)
|
| 15 |
+
cs = float(pred.get("coherence_score", -1))
|
| 16 |
+
band = str(pred.get("risk_band", "")).strip().lower()
|
| 17 |
+
except Exception:
|
| 18 |
+
return ScoreResult(0.0, {"error":"parse_fail","id":sample.get("id")})
|
| 19 |
+
|
| 20 |
+
true_cs_raw = sample.get("coherence_score", "")
|
| 21 |
+
true_band_raw = sample.get("stochastic_risk_band", "")
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
true_cs = float(true_cs_raw) if true_cs_raw not in ("", None) else None
|
| 25 |
+
except Exception:
|
| 26 |
+
true_cs = None
|
| 27 |
+
|
| 28 |
+
true_band = str(true_band_raw).strip().lower() if true_band_raw not in ("", None) else ""
|
| 29 |
+
|
| 30 |
+
# format-only if no ground truth
|
| 31 |
+
if true_cs is None or true_band == "":
|
| 32 |
+
ok = (0.0 <= cs <= 1.0) and (band in BANDS)
|
| 33 |
+
return ScoreResult(1.0 if ok else 0.0, {"mode":"format_only","id":sample.get("id")})
|
| 34 |
+
|
| 35 |
+
cs_err = abs(true_cs - cs)
|
| 36 |
+
cs_score = max(0.0, 1.0 - cs_err)
|
| 37 |
+
band_score = 1.0 if band == true_band else 0.0
|
| 38 |
+
|
| 39 |
+
total = 0.65 * cs_score + 0.35 * band_score
|
| 40 |
+
return ScoreResult(total, {"id":sample.get("id"),"cs":cs,"true_cs":true_cs,"band":band,"true_band":true_band})
|
| 41 |
+
|
| 42 |
+
def aggregate(results: List[ScoreResult]) -> Dict[str, Any]:
|
| 43 |
+
if not results:
|
| 44 |
+
return {"mean":0.0,"n":0}
|
| 45 |
+
return {"mean": sum(r.score for r in results)/len(results), "n": len(results)}
|