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+
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(
|
| 68 |
+
rows: List[Dict[str, str]], id_column: Optional[str]
|
| 69 |
+
) -> Dict[str, Dict[str, str]]:
|
| 70 |
+
if not id_column:
|
| 71 |
+
return {str(i): row for i, row in enumerate(rows)}
|
| 72 |
+
return {str(row[id_column]): row for row in rows}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _detect_join_key(
|
| 76 |
+
reference_fields: List[str], prediction_fields: List[str]
|
| 77 |
+
) -> Optional[str]:
|
| 78 |
+
preferred_keys = ["id", "row_id", "sample_id", "case_id", "record_id"]
|
| 79 |
+
for key in preferred_keys:
|
| 80 |
+
if key in reference_fields and key in prediction_fields:
|
| 81 |
+
return key
|
| 82 |
+
return None
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _build_y_true_y_pred(
|
| 86 |
+
reference_rows: List[Dict[str, str]],
|
| 87 |
+
prediction_rows: List[Dict[str, str]],
|
| 88 |
+
label_col: str,
|
| 89 |
+
pred_label_col: Optional[str],
|
| 90 |
+
pred_score_col: Optional[str],
|
| 91 |
+
threshold: float,
|
| 92 |
+
) -> Tuple[List[int], List[int], List[float], Dict[str, int], List[Dict[str, str]]]:
|
| 93 |
+
if not prediction_rows:
|
| 94 |
+
raise ValueError("Predictions file is empty.")
|
| 95 |
+
|
| 96 |
+
ref_fields = list(reference_rows[0].keys())
|
| 97 |
+
pred_fields = list(prediction_rows[0].keys())
|
| 98 |
+
join_key = _detect_join_key(ref_fields, pred_fields)
|
| 99 |
+
pred_index = _index_prediction_rows(prediction_rows, join_key)
|
| 100 |
+
|
| 101 |
+
y_true: List[int] = []
|
| 102 |
+
y_pred: List[int] = []
|
| 103 |
+
y_score: List[float] = []
|
| 104 |
+
matched_reference_rows: List[Dict[str, str]] = []
|
| 105 |
+
|
| 106 |
+
matched_rows = 0
|
| 107 |
+
missing_predictions = 0
|
| 108 |
+
|
| 109 |
+
for i, ref_row in enumerate(reference_rows):
|
| 110 |
+
ref_lookup = str(ref_row[join_key]) if join_key else str(i)
|
| 111 |
+
pred_row = pred_index.get(ref_lookup)
|
| 112 |
+
|
| 113 |
+
if pred_row is None:
|
| 114 |
+
missing_predictions += 1
|
| 115 |
+
continue
|
| 116 |
+
|
| 117 |
+
true_label = _normalize_binary(ref_row.get(label_col, 0))
|
| 118 |
+
|
| 119 |
+
if pred_label_col and pred_label_col in pred_row:
|
| 120 |
+
pred_label = _normalize_binary(pred_row.get(pred_label_col, 0))
|
| 121 |
+
pred_score = float(pred_label)
|
| 122 |
+
elif pred_score_col and pred_score_col in pred_row:
|
| 123 |
+
pred_score = _safe_float(pred_row.get(pred_score_col, 0.0))
|
| 124 |
+
pred_label = 1 if pred_score >= threshold else 0
|
| 125 |
+
else:
|
| 126 |
+
raise ValueError(
|
| 127 |
+
"No usable prediction column found. Provide a binary prediction column "
|
| 128 |
+
"or a score column such as prediction_score."
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
y_true.append(true_label)
|
| 132 |
+
y_pred.append(pred_label)
|
| 133 |
+
y_score.append(pred_score)
|
| 134 |
+
matched_reference_rows.append(ref_row)
|
| 135 |
+
matched_rows += 1
|
| 136 |
+
|
| 137 |
+
support = {
|
| 138 |
+
"reference_rows": len(reference_rows),
|
| 139 |
+
"prediction_rows": len(prediction_rows),
|
| 140 |
+
"matched_rows": matched_rows,
|
| 141 |
+
"missing_predictions": missing_predictions,
|
| 142 |
+
"join_key_used": 0 if join_key is None else 1,
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
if matched_rows == 0:
|
| 146 |
+
raise ValueError("No rows could be matched between reference and prediction files.")
|
| 147 |
+
|
| 148 |
+
return y_true, y_pred, y_score, support, matched_reference_rows
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _confusion_matrix(y_true: List[int], y_pred: List[int]) -> Dict[str, int]:
|
| 152 |
+
tp = tn = fp = fn = 0
|
| 153 |
+
for truth, pred in zip(y_true, y_pred):
|
| 154 |
+
if truth == 1 and pred == 1:
|
| 155 |
+
tp += 1
|
| 156 |
+
elif truth == 0 and pred == 0:
|
| 157 |
+
tn += 1
|
| 158 |
+
elif truth == 0 and pred == 1:
|
| 159 |
+
fp += 1
|
| 160 |
+
elif truth == 1 and pred == 0:
|
| 161 |
+
fn += 1
|
| 162 |
+
return {"tp": tp, "tn": tn, "fp": fp, "fn": fn}
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _accuracy(tp: int, tn: int, fp: int, fn: int) -> float:
|
| 166 |
+
denom = tp + tn + fp + fn
|
| 167 |
+
return (tp + tn) / denom if denom else 0.0
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _precision(tp: int, fp: int) -> float:
|
| 171 |
+
denom = tp + fp
|
| 172 |
+
return tp / denom if denom else 0.0
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _recall(tp: int, fn: int) -> float:
|
| 176 |
+
denom = tp + fn
|
| 177 |
+
return tp / denom if denom else 0.0
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _f1(precision: float, recall: float) -> float:
|
| 181 |
+
denom = precision + recall
|
| 182 |
+
return 2 * precision * recall / denom if denom else 0.0
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _trajectory_diagnostics(
|
| 186 |
+
reference_rows: List[Dict[str, str]],
|
| 187 |
+
y_true: List[int],
|
| 188 |
+
y_pred: List[int],
|
| 189 |
+
) -> Dict[str, float]:
|
| 190 |
+
if not reference_rows or "drift_gradient" not in reference_rows[0]:
|
| 191 |
+
return {
|
| 192 |
+
"trajectory_positive_support": 0,
|
| 193 |
+
"recall_trajectory_deterioration_detection": 0.0,
|
| 194 |
+
"false_stable_trajectory_rate": 0.0,
|
| 195 |
+
"trajectory_label_alignment_rate": 0.0,
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
trajectory_positive_support = 0
|
| 199 |
+
trajectory_detected_tp = 0
|
| 200 |
+
trajectory_false_stable = 0
|
| 201 |
+
trajectory_alignment_hits = 0
|
| 202 |
+
|
| 203 |
+
for row, truth, pred in zip(reference_rows, y_true, y_pred):
|
| 204 |
+
drift_gradient = _safe_float(row.get("drift_gradient", 0.0))
|
| 205 |
+
worsening_trajectory = 1 if drift_gradient > 0 else 0
|
| 206 |
+
|
| 207 |
+
if worsening_trajectory == 1:
|
| 208 |
+
trajectory_positive_support += 1
|
| 209 |
+
if pred == 1:
|
| 210 |
+
trajectory_detected_tp += 1
|
| 211 |
+
if pred == 0:
|
| 212 |
+
trajectory_false_stable += 1
|
| 213 |
+
|
| 214 |
+
if worsening_trajectory == truth:
|
| 215 |
+
trajectory_alignment_hits += 1
|
| 216 |
+
|
| 217 |
+
recall_trajectory_deterioration_detection = (
|
| 218 |
+
trajectory_detected_tp / trajectory_positive_support
|
| 219 |
+
if trajectory_positive_support
|
| 220 |
+
else 0.0
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
false_stable_trajectory_rate = (
|
| 224 |
+
trajectory_false_stable / trajectory_positive_support
|
| 225 |
+
if trajectory_positive_support
|
| 226 |
+
else 0.0
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
trajectory_label_alignment_rate = (
|
| 230 |
+
trajectory_alignment_hits / len(reference_rows)
|
| 231 |
+
if reference_rows
|
| 232 |
+
else 0.0
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
return {
|
| 236 |
+
"trajectory_positive_support": trajectory_positive_support,
|
| 237 |
+
"recall_trajectory_deterioration_detection": recall_trajectory_deterioration_detection,
|
| 238 |
+
"false_stable_trajectory_rate": false_stable_trajectory_rate,
|
| 239 |
+
"trajectory_label_alignment_rate": trajectory_label_alignment_rate,
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def score(
|
| 244 |
+
reference_path: str = DEFAULT_REFERENCE_PATH,
|
| 245 |
+
predictions_path: str = DEFAULT_PREDICTIONS_PATH,
|
| 246 |
+
threshold: float = 0.5,
|
| 247 |
+
) -> Dict[str, object]:
|
| 248 |
+
reference_rows = _read_csv(reference_path)
|
| 249 |
+
prediction_rows = _read_csv(predictions_path)
|
| 250 |
+
|
| 251 |
+
if not reference_rows:
|
| 252 |
+
raise ValueError("Reference file is empty.")
|
| 253 |
+
|
| 254 |
+
label_col = _find_label_column(list(reference_rows[0].keys()))
|
| 255 |
+
pred_label_col, pred_score_col = _find_prediction_columns(list(prediction_rows[0].keys()))
|
| 256 |
+
|
| 257 |
+
y_true, y_pred, y_score, support, matched_reference_rows = _build_y_true_y_pred(
|
| 258 |
+
reference_rows=reference_rows,
|
| 259 |
+
prediction_rows=prediction_rows,
|
| 260 |
+
label_col=label_col,
|
| 261 |
+
pred_label_col=pred_label_col,
|
| 262 |
+
pred_score_col=pred_score_col,
|
| 263 |
+
threshold=threshold,
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
cm = _confusion_matrix(y_true, y_pred)
|
| 267 |
+
precision = _precision(cm["tp"], cm["fp"])
|
| 268 |
+
recall = _recall(cm["tp"], cm["fn"])
|
| 269 |
+
accuracy = _accuracy(cm["tp"], cm["tn"], cm["fp"], cm["fn"])
|
| 270 |
+
f1 = _f1(precision, recall)
|
| 271 |
+
|
| 272 |
+
trajectory_metrics = _trajectory_diagnostics(
|
| 273 |
+
reference_rows=matched_reference_rows,
|
| 274 |
+
y_true=y_true,
|
| 275 |
+
y_pred=y_pred,
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
return {
|
| 279 |
+
"label_column": label_col,
|
| 280 |
+
"prediction_label_column": pred_label_col,
|
| 281 |
+
"prediction_score_column": pred_score_col,
|
| 282 |
+
"primary_metric": "recall_trajectory_deterioration_detection",
|
| 283 |
+
"secondary_metric": "false_stable_trajectory_rate",
|
| 284 |
+
"threshold_transparency": {
|
| 285 |
+
"score_threshold_used": threshold if pred_score_col else None,
|
| 286 |
+
"threshold_applied_to_score_column": pred_score_col,
|
| 287 |
+
"predictions_interpreted_as": (
|
| 288 |
+
"binary labels from prediction column"
|
| 289 |
+
if pred_label_col
|
| 290 |
+
else "binary labels thresholded from score column"
|
| 291 |
+
),
|
| 292 |
+
},
|
| 293 |
+
"support": {
|
| 294 |
+
**support,
|
| 295 |
+
"positive_label_support": sum(y_true),
|
| 296 |
+
"negative_label_support": len(y_true) - sum(y_true),
|
| 297 |
+
"predicted_positive_support": sum(y_pred),
|
| 298 |
+
"predicted_negative_support": len(y_pred) - sum(y_pred),
|
| 299 |
+
},
|
| 300 |
+
"metrics": {
|
| 301 |
+
"accuracy": round(accuracy, 4),
|
| 302 |
+
"precision": round(precision, 4),
|
| 303 |
+
"recall": round(recall, 4),
|
| 304 |
+
"f1": round(f1, 4),
|
| 305 |
+
"recall_trajectory_deterioration_detection": round(
|
| 306 |
+
trajectory_metrics["recall_trajectory_deterioration_detection"], 4
|
| 307 |
+
),
|
| 308 |
+
"false_stable_trajectory_rate": round(
|
| 309 |
+
trajectory_metrics["false_stable_trajectory_rate"], 4
|
| 310 |
+
),
|
| 311 |
+
"trajectory_label_alignment_rate": round(
|
| 312 |
+
trajectory_metrics["trajectory_label_alignment_rate"], 4
|
| 313 |
+
),
|
| 314 |
+
},
|
| 315 |
+
"confusion_matrix": cm,
|
| 316 |
+
"trajectory_support": {
|
| 317 |
+
"trajectory_positive_support": trajectory_metrics["trajectory_positive_support"],
|
| 318 |
+
},
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
if __name__ == "__main__":
|
| 323 |
+
reference_path = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_REFERENCE_PATH
|
| 324 |
+
predictions_path = sys.argv[2] if len(sys.argv) > 2 else DEFAULT_PREDICTIONS_PATH
|
| 325 |
+
threshold = float(sys.argv[3]) if len(sys.argv) > 3 else 0.5
|
| 326 |
+
|
| 327 |
+
output = score(
|
| 328 |
+
reference_path=reference_path,
|
| 329 |
+
predictions_path=predictions_path,
|
| 330 |
+
threshold=threshold,
|
| 331 |
+
)
|
| 332 |
+
print(json.dumps(output, indent=2))
|