ClarusC64 commited on
Commit
e6c882a
·
verified ·
1 Parent(s): 1d04f10

Create scorer.py

Browse files
Files changed (1) hide show
  1. scorer.py +328 -0
scorer.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv
2
+ import json
3
+ import sys
4
+ from typing import Dict, List, Optional, Tuple
5
+
6
+
7
+ DEFAULT_REFERENCE_PATH = "data/tester.csv"
8
+ DEFAULT_PREDICTIONS_PATH = "predictions.csv"
9
+
10
+
11
+ def _safe_float(value, default: float = 0.0) -> float:
12
+ try:
13
+ return float(value)
14
+ except (TypeError, ValueError):
15
+ return default
16
+
17
+
18
+ def _normalize_binary(value) -> int:
19
+ value_str = str(value).strip().lower()
20
+ if value_str in {"1", "true", "yes", "y", "positive", "fail", "failure"}:
21
+ return 1
22
+ return 0
23
+
24
+
25
+ def _read_csv(path: str) -> List[Dict[str, str]]:
26
+ with open(path, "r", encoding="utf-8") as f:
27
+ return list(csv.DictReader(f))
28
+
29
+
30
+ def _find_label_column(fieldnames: List[str]) -> str:
31
+ label_candidates = [col for col in fieldnames if col.startswith("label_")]
32
+ if len(label_candidates) == 1:
33
+ return label_candidates[0]
34
+ if not label_candidates:
35
+ raise ValueError("No label column found. Expected a column starting with 'label_'.")
36
+ raise ValueError(
37
+ f"Multiple label columns found: {label_candidates}. Expected exactly one label column."
38
+ )
39
+
40
+
41
+ def _find_prediction_columns(fieldnames: List[str]) -> Tuple[Optional[str], Optional[str]]:
42
+ pred_label_candidates = [
43
+ "prediction",
44
+ "pred",
45
+ "predicted_label",
46
+ "prediction_label",
47
+ "label_pred",
48
+ "y_pred",
49
+ "output",
50
+ ]
51
+ pred_score_candidates = [
52
+ "prediction_score",
53
+ "pred_score",
54
+ "score",
55
+ "probability",
56
+ "prob",
57
+ "confidence",
58
+ "risk_score",
59
+ "y_score",
60
+ ]
61
+
62
+ pred_label_col = next((c for c in pred_label_candidates if c in fieldnames), None)
63
+ pred_score_col = next((c for c in pred_score_candidates if c in fieldnames), None)
64
+ return pred_label_col, pred_score_col
65
+
66
+
67
+ def _index_prediction_rows(rows: List[Dict[str, str]], id_column: Optional[str]) -> Dict[str, Dict[str, str]]:
68
+ if not id_column:
69
+ return {str(i): row for i, row in enumerate(rows)}
70
+ return {str(row[id_column]): row for row in rows}
71
+
72
+
73
+ def _detect_join_key(reference_fields: List[str], prediction_fields: List[str]) -> Optional[str]:
74
+ preferred_keys = ["id", "row_id", "sample_id", "case_id", "record_id"]
75
+ for key in preferred_keys:
76
+ if key in reference_fields and key in prediction_fields:
77
+ return key
78
+ return None
79
+
80
+
81
+ def _build_y_true_y_pred(
82
+ reference_rows: List[Dict[str, str]],
83
+ prediction_rows: List[Dict[str, str]],
84
+ label_col: str,
85
+ pred_label_col: Optional[str],
86
+ pred_score_col: Optional[str],
87
+ threshold: float,
88
+ ) -> Tuple[List[int], List[int], List[float], Dict[str, int], List[Dict[str, str]]]:
89
+ if not prediction_rows:
90
+ raise ValueError("Predictions file is empty.")
91
+
92
+ ref_fields = list(reference_rows[0].keys())
93
+ pred_fields = list(prediction_rows[0].keys())
94
+ join_key = _detect_join_key(ref_fields, pred_fields)
95
+ pred_index = _index_prediction_rows(prediction_rows, join_key)
96
+
97
+ y_true: List[int] = []
98
+ y_pred: List[int] = []
99
+ y_score: List[float] = []
100
+ matched_reference_rows: List[Dict[str, str]] = []
101
+
102
+ matched_rows = 0
103
+ missing_predictions = 0
104
+
105
+ for i, ref_row in enumerate(reference_rows):
106
+ ref_lookup = str(ref_row[join_key]) if join_key else str(i)
107
+ pred_row = pred_index.get(ref_lookup)
108
+
109
+ if pred_row is None:
110
+ missing_predictions += 1
111
+ continue
112
+
113
+ true_label = _normalize_binary(ref_row.get(label_col, 0))
114
+
115
+ if pred_label_col and pred_label_col in pred_row:
116
+ pred_label = _normalize_binary(pred_row.get(pred_label_col, 0))
117
+ pred_score = float(pred_label)
118
+ elif pred_score_col and pred_score_col in pred_row:
119
+ pred_score = _safe_float(pred_row.get(pred_score_col, 0.0))
120
+ pred_label = 1 if pred_score >= threshold else 0
121
+ else:
122
+ raise ValueError(
123
+ "No usable prediction column found. Provide a binary prediction column "
124
+ "or a score column such as prediction_score."
125
+ )
126
+
127
+ y_true.append(true_label)
128
+ y_pred.append(pred_label)
129
+ y_score.append(pred_score)
130
+ matched_reference_rows.append(ref_row)
131
+ matched_rows += 1
132
+
133
+ support = {
134
+ "reference_rows": len(reference_rows),
135
+ "prediction_rows": len(prediction_rows),
136
+ "matched_rows": matched_rows,
137
+ "missing_predictions": missing_predictions,
138
+ "join_key_used": 0 if join_key is None else 1,
139
+ }
140
+
141
+ if matched_rows == 0:
142
+ raise ValueError("No rows could be matched between reference and prediction files.")
143
+
144
+ return y_true, y_pred, y_score, support, matched_reference_rows
145
+
146
+
147
+ def _confusion_matrix(y_true: List[int], y_pred: List[int]) -> Dict[str, int]:
148
+ tp = tn = fp = fn = 0
149
+ for truth, pred in zip(y_true, y_pred):
150
+ if truth == 1 and pred == 1:
151
+ tp += 1
152
+ elif truth == 0 and pred == 0:
153
+ tn += 1
154
+ elif truth == 0 and pred == 1:
155
+ fp += 1
156
+ elif truth == 1 and pred == 0:
157
+ fn += 1
158
+ return {"tp": tp, "tn": tn, "fp": fp, "fn": fn}
159
+
160
+
161
+ def _accuracy(tp: int, tn: int, fp: int, fn: int) -> float:
162
+ denom = tp + tn + fp + fn
163
+ return (tp + tn) / denom if denom else 0.0
164
+
165
+
166
+ def _precision(tp: int, fp: int) -> float:
167
+ denom = tp + fp
168
+ return tp / denom if denom else 0.0
169
+
170
+
171
+ def _recall(tp: int, fn: int) -> float:
172
+ denom = tp + fn
173
+ return tp / denom if denom else 0.0
174
+
175
+
176
+ def _f1(precision: float, recall: float) -> float:
177
+ denom = precision + recall
178
+ return 2 * precision * recall / denom if denom else 0.0
179
+
180
+
181
+ def _trajectory_diagnostics(
182
+ reference_rows: List[Dict[str, str]],
183
+ y_true: List[int],
184
+ y_pred: List[int],
185
+ ) -> Dict[str, float]:
186
+ if not reference_rows or "drift_gradient" not in reference_rows[0]:
187
+ return {
188
+ "trajectory_positive_support": 0,
189
+ "recall_trajectory_deterioration_detection": 0.0,
190
+ "false_stable_trajectory_rate": 0.0,
191
+ "trajectory_label_alignment_rate": 0.0,
192
+ }
193
+
194
+ trajectory_positive_support = 0
195
+ trajectory_detected_tp = 0
196
+ trajectory_false_stable = 0
197
+ trajectory_alignment_hits = 0
198
+
199
+ for row, truth, pred in zip(reference_rows, y_true, y_pred):
200
+ drift_gradient = _safe_float(row.get("drift_gradient", 0.0))
201
+ worsening_trajectory = 1 if drift_gradient > 0 else 0
202
+
203
+ if worsening_trajectory == 1:
204
+ trajectory_positive_support += 1
205
+ if pred == 1:
206
+ trajectory_detected_tp += 1
207
+ if pred == 0:
208
+ trajectory_false_stable += 1
209
+
210
+ if worsening_trajectory == truth:
211
+ trajectory_alignment_hits += 1
212
+
213
+ recall_trajectory_deterioration_detection = (
214
+ trajectory_detected_tp / trajectory_positive_support
215
+ if trajectory_positive_support
216
+ else 0.0
217
+ )
218
+
219
+ false_stable_trajectory_rate = (
220
+ trajectory_false_stable / trajectory_positive_support
221
+ if trajectory_positive_support
222
+ else 0.0
223
+ )
224
+
225
+ trajectory_label_alignment_rate = (
226
+ trajectory_alignment_hits / len(reference_rows)
227
+ if reference_rows
228
+ else 0.0
229
+ )
230
+
231
+ return {
232
+ "trajectory_positive_support": trajectory_positive_support,
233
+ "recall_trajectory_deterioration_detection": recall_trajectory_deterioration_detection,
234
+ "false_stable_trajectory_rate": false_stable_trajectory_rate,
235
+ "trajectory_label_alignment_rate": trajectory_label_alignment_rate,
236
+ }
237
+
238
+
239
+ def score(
240
+ reference_path: str = DEFAULT_REFERENCE_PATH,
241
+ predictions_path: str = DEFAULT_PREDICTIONS_PATH,
242
+ threshold: float = 0.5,
243
+ ) -> Dict[str, object]:
244
+ reference_rows = _read_csv(reference_path)
245
+ prediction_rows = _read_csv(predictions_path)
246
+
247
+ if not reference_rows:
248
+ raise ValueError("Reference file is empty.")
249
+
250
+ label_col = _find_label_column(list(reference_rows[0].keys()))
251
+ pred_label_col, pred_score_col = _find_prediction_columns(list(prediction_rows[0].keys()))
252
+
253
+ y_true, y_pred, y_score, support, matched_reference_rows = _build_y_true_y_pred(
254
+ reference_rows=reference_rows,
255
+ prediction_rows=prediction_rows,
256
+ label_col=label_col,
257
+ pred_label_col=pred_label_col,
258
+ pred_score_col=pred_score_col,
259
+ threshold=threshold,
260
+ )
261
+
262
+ cm = _confusion_matrix(y_true, y_pred)
263
+ precision = _precision(cm["tp"], cm["fp"])
264
+ recall = _recall(cm["tp"], cm["fn"])
265
+ accuracy = _accuracy(cm["tp"], cm["tn"], cm["fp"], cm["fn"])
266
+ f1 = _f1(precision, recall)
267
+
268
+ trajectory_metrics = _trajectory_diagnostics(
269
+ reference_rows=matched_reference_rows,
270
+ y_true=y_true,
271
+ y_pred=y_pred,
272
+ )
273
+
274
+ return {
275
+ "label_column": label_col,
276
+ "prediction_label_column": pred_label_col,
277
+ "prediction_score_column": pred_score_col,
278
+ "primary_metric": "recall_trajectory_deterioration_detection",
279
+ "secondary_metric": "false_stable_trajectory_rate",
280
+ "threshold_transparency": {
281
+ "score_threshold_used": threshold if pred_score_col else None,
282
+ "threshold_applied_to_score_column": pred_score_col,
283
+ "predictions_interpreted_as": (
284
+ "binary labels from prediction column"
285
+ if pred_label_col
286
+ else "binary labels thresholded from score column"
287
+ ),
288
+ },
289
+ "support": {
290
+ **support,
291
+ "positive_label_support": sum(y_true),
292
+ "negative_label_support": len(y_true) - sum(y_true),
293
+ "predicted_positive_support": sum(y_pred),
294
+ "predicted_negative_support": len(y_pred) - sum(y_pred),
295
+ },
296
+ "metrics": {
297
+ "accuracy": round(accuracy, 4),
298
+ "precision": round(precision, 4),
299
+ "recall": round(recall, 4),
300
+ "f1": round(f1, 4),
301
+ "recall_trajectory_deterioration_detection": round(
302
+ trajectory_metrics["recall_trajectory_deterioration_detection"], 4
303
+ ),
304
+ "false_stable_trajectory_rate": round(
305
+ trajectory_metrics["false_stable_trajectory_rate"], 4
306
+ ),
307
+ "trajectory_label_alignment_rate": round(
308
+ trajectory_metrics["trajectory_label_alignment_rate"], 4
309
+ ),
310
+ },
311
+ "confusion_matrix": cm,
312
+ "trajectory_support": {
313
+ "trajectory_positive_support": trajectory_metrics["trajectory_positive_support"],
314
+ },
315
+ }
316
+
317
+
318
+ if __name__ == "__main__":
319
+ reference_path = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_REFERENCE_PATH
320
+ predictions_path = sys.argv[2] if len(sys.argv) > 2 else DEFAULT_PREDICTIONS_PATH
321
+ threshold = float(sys.argv[3]) if len(sys.argv) > 3 else 0.5
322
+
323
+ output = score(
324
+ reference_path=reference_path,
325
+ predictions_path=predictions_path,
326
+ threshold=threshold,
327
+ )
328
+ print(json.dumps(output, indent=2))