File size: 3,456 Bytes
7b82fe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import csv
import sys
from pathlib import Path


def load_csv(path):
    with open(path, "r", encoding="utf-8") as f:
        return list(csv.DictReader(f))


def normalize_binary(value):
    if isinstance(value, int):
        return value
    text = str(value).strip().lower()
    if text in {"1", "true", "yes", "positive"}:
        return 1
    if text in {"0", "false", "no", "negative"}:
        return 0
    raise ValueError(f"Unrecognized binary value: {value}")


def find_label_column(fieldnames):
    matches = [c for c in fieldnames if c.startswith("label_")]
    if len(matches) != 1:
        raise ValueError(f"Expected exactly one label_ column, found: {matches}")
    return matches[0]


def compute_metrics(y_true, y_pred):
    tp = sum(1 for t, p in zip(y_true, y_pred) if t == 1 and p == 1)
    tn = sum(1 for t, p in zip(y_true, y_pred) if t == 0 and p == 0)
    fp = sum(1 for t, p in zip(y_true, y_pred) if t == 0 and p == 1)
    fn = sum(1 for t, p in zip(y_true, y_pred) if t == 1 and p == 0)

    total = len(y_true)
    accuracy = (tp + tn) / total if total else 0.0
    precision = tp / (tp + fp) if (tp + fp) else 0.0
    recall_successful_stabilization = tp / (tp + fn) if (tp + fn) else 0.0
    failed_rescue_rate = fn / (fn + tp) if (fn + tp) else 0.0
    f1 = (
        2 * precision * recall_successful_stabilization / (precision + recall_successful_stabilization)
        if (precision + recall_successful_stabilization)
        else 0.0
    )

    return {
        "accuracy": accuracy,
        "precision": precision,
        "recall_successful_stabilization": recall_successful_stabilization,
        "failed_rescue_rate": failed_rescue_rate,
        "f1": f1,
        "primary_metric": "recall_successful_stabilization",
        "secondary_metric": "failed_rescue_rate",
        "confusion_matrix": {
            "true_positives": tp,
            "false_positives": fp,
            "true_negatives": tn,
            "false_negatives": fn,
        },
    }


def score(reference_path, prediction_path):
    references = load_csv(reference_path)
    predictions = load_csv(prediction_path)

    if not references:
        raise ValueError("Reference file is empty.")
    if not predictions:
        raise ValueError("Prediction file is empty.")
    if len(references) != len(predictions):
        raise ValueError("Reference and prediction row counts do not match.")

    label_col = find_label_column(references[0].keys())

    y_true = [normalize_binary(row[label_col]) for row in references]

    pred_col = None
    for candidate in ["prediction", "predicted_label", label_col]:
        if candidate in predictions[0]:
            pred_col = candidate
            break

    if pred_col is None:
        raise ValueError(
            "Prediction file must contain one of: prediction, predicted_label, or the label column name."
        )

    y_pred = [normalize_binary(row[pred_col]) for row in predictions]

    return compute_metrics(y_true, y_pred)


if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python scorer.py <reference.csv> <predictions.csv>", file=sys.stderr)
        sys.exit(1)

    ref_path = Path(sys.argv[1])
    pred_path = Path(sys.argv[2])

    try:
        results = score(ref_path, pred_path)
    except Exception as e:
        print(f"Scoring error: {e}", file=sys.stderr)
        sys.exit(1)

    for key, value in results.items():
        print(f"{key}: {value}")