Create scorer.py
Browse files
scorer.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from typing import Dict, Any, List
|
| 3 |
+
|
| 4 |
+
@dataclass
|
| 5 |
+
class ScoreResult:
|
| 6 |
+
score: float
|
| 7 |
+
details: Dict[str, Any]
|
| 8 |
+
|
| 9 |
+
def parse(prediction: str):
|
| 10 |
+
try:
|
| 11 |
+
parts = prediction.strip().split(",")
|
| 12 |
+
drift_score = float(parts[0])
|
| 13 |
+
drift_flag = int(parts[1])
|
| 14 |
+
return drift_score, drift_flag
|
| 15 |
+
except Exception:
|
| 16 |
+
return None, None
|
| 17 |
+
|
| 18 |
+
def score(sample: Dict[str, Any], prediction: str) -> ScoreResult:
|
| 19 |
+
pred_score, pred_flag = parse(prediction)
|
| 20 |
+
if pred_score is None:
|
| 21 |
+
return ScoreResult(0.0, {"error": "parse failure"})
|
| 22 |
+
|
| 23 |
+
true_score = sample.get("drift_score", "")
|
| 24 |
+
true_flag = sample.get("drift_flag", "")
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
true_score = float(true_score)
|
| 28 |
+
true_flag = int(true_flag)
|
| 29 |
+
except:
|
| 30 |
+
true_score = None
|
| 31 |
+
|
| 32 |
+
if true_score is None:
|
| 33 |
+
valid = 0 <= pred_score <= 1 and pred_flag in (0,1)
|
| 34 |
+
return ScoreResult(1.0 if valid else 0.0, {"mode": "format_only"})
|
| 35 |
+
|
| 36 |
+
err = abs(true_score - pred_score)
|
| 37 |
+
score_val = max(0.0, 1.0 - err)
|
| 38 |
+
if pred_flag == true_flag:
|
| 39 |
+
score_val += 0.25
|
| 40 |
+
|
| 41 |
+
return ScoreResult(min(score_val,1.0), {
|
| 42 |
+
"pred_score": pred_score,
|
| 43 |
+
"true_score": true_score,
|
| 44 |
+
"pred_flag": pred_flag,
|
| 45 |
+
"true_flag": true_flag
|
| 46 |
+
})
|
| 47 |
+
|
| 48 |
+
def aggregate(results: List[ScoreResult]):
|
| 49 |
+
if not results:
|
| 50 |
+
return {"mean":0,"n":0}
|
| 51 |
+
return {"mean": sum(r.score for r in results)/len(results), "n": len(results)}
|