| import csv |
| import json |
| import sys |
| from typing import Dict, List, Optional, Tuple |
|
|
|
|
| DEFAULT_REFERENCE_PATH = "data/tester.csv" |
| DEFAULT_PREDICTIONS_PATH = "predictions.csv" |
|
|
|
|
| def _safe_float(value, default: float = 0.0) -> float: |
| try: |
| return float(value) |
| except (TypeError, ValueError): |
| return default |
|
|
|
|
| def _normalize_binary(value) -> int: |
| value_str = str(value).strip().lower() |
| if value_str in {"1", "true", "yes", "y", "positive", "fail", "failure"}: |
| return 1 |
| return 0 |
|
|
|
|
| def _read_csv(path: str) -> List[Dict[str, str]]: |
| with open(path, "r", encoding="utf-8") as f: |
| return list(csv.DictReader(f)) |
|
|
|
|
| def _find_label_column(fieldnames: List[str]) -> str: |
| label_candidates = [col for col in fieldnames if col.startswith("label_")] |
| if len(label_candidates) == 1: |
| return label_candidates[0] |
| if not label_candidates: |
| raise ValueError("No label column found. Expected a column starting with 'label_'.") |
| raise ValueError( |
| f"Multiple label columns found: {label_candidates}. Expected exactly one label column." |
| ) |
|
|
|
|
| def _find_prediction_columns(fieldnames: List[str]) -> Tuple[Optional[str], Optional[str]]: |
| pred_label_candidates = [ |
| "prediction", |
| "pred", |
| "predicted_label", |
| "prediction_label", |
| "label_pred", |
| "y_pred", |
| "output", |
| ] |
| pred_score_candidates = [ |
| "prediction_score", |
| "pred_score", |
| "score", |
| "probability", |
| "prob", |
| "confidence", |
| "risk_score", |
| "y_score", |
| ] |
|
|
| pred_label_col = next((c for c in pred_label_candidates if c in fieldnames), None) |
| pred_score_col = next((c for c in pred_score_candidates if c in fieldnames), None) |
| return pred_label_col, pred_score_col |
|
|
|
|
| def _index_prediction_rows(rows: List[Dict[str, str]], id_column: Optional[str]) -> Dict[str, Dict[str, str]]: |
| if not id_column: |
| return {str(i): row for i, row in enumerate(rows)} |
| return {str(row[id_column]): row for row in rows} |
|
|
|
|
| def _detect_join_key(reference_fields: List[str], prediction_fields: List[str]) -> Optional[str]: |
| preferred_keys = ["id", "row_id", "sample_id", "case_id", "record_id"] |
| for key in preferred_keys: |
| if key in reference_fields and key in prediction_fields: |
| return key |
| return None |
|
|
|
|
| def _build_y_true_y_pred( |
| reference_rows: List[Dict[str, str]], |
| prediction_rows: List[Dict[str, str]], |
| label_col: str, |
| pred_label_col: Optional[str], |
| pred_score_col: Optional[str], |
| threshold: float, |
| ) -> Tuple[List[int], List[int], List[float], Dict[str, int], List[Dict[str, str]]]: |
| if not prediction_rows: |
| raise ValueError("Predictions file is empty.") |
|
|
| ref_fields = list(reference_rows[0].keys()) |
| pred_fields = list(prediction_rows[0].keys()) |
| join_key = _detect_join_key(ref_fields, pred_fields) |
| pred_index = _index_prediction_rows(prediction_rows, join_key) |
|
|
| y_true: List[int] = [] |
| y_pred: List[int] = [] |
| y_score: List[float] = [] |
| matched_reference_rows: List[Dict[str, str]] = [] |
|
|
| matched_rows = 0 |
| missing_predictions = 0 |
|
|
| for i, ref_row in enumerate(reference_rows): |
| ref_lookup = str(ref_row[join_key]) if join_key else str(i) |
| pred_row = pred_index.get(ref_lookup) |
|
|
| if pred_row is None: |
| missing_predictions += 1 |
| continue |
|
|
| true_label = _normalize_binary(ref_row.get(label_col, 0)) |
|
|
| if pred_label_col and pred_label_col in pred_row: |
| pred_label = _normalize_binary(pred_row.get(pred_label_col, 0)) |
| pred_score = float(pred_label) |
| elif pred_score_col and pred_score_col in pred_row: |
| pred_score = _safe_float(pred_row.get(pred_score_col, 0.0)) |
| pred_label = 1 if pred_score >= threshold else 0 |
| else: |
| raise ValueError( |
| "No usable prediction column found. Provide a binary prediction column " |
| "or a score column such as prediction_score." |
| ) |
|
|
| y_true.append(true_label) |
| y_pred.append(pred_label) |
| y_score.append(pred_score) |
| matched_reference_rows.append(ref_row) |
| matched_rows += 1 |
|
|
| support = { |
| "reference_rows": len(reference_rows), |
| "prediction_rows": len(prediction_rows), |
| "matched_rows": matched_rows, |
| "missing_predictions": missing_predictions, |
| "join_key_used": 0 if join_key is None else 1, |
| } |
|
|
| if matched_rows == 0: |
| raise ValueError("No rows could be matched between reference and prediction files.") |
|
|
| return y_true, y_pred, y_score, support, matched_reference_rows |
|
|
|
|
| def _confusion_matrix(y_true: List[int], y_pred: List[int]) -> Dict[str, int]: |
| tp = tn = fp = fn = 0 |
| for truth, pred in zip(y_true, y_pred): |
| if truth == 1 and pred == 1: |
| tp += 1 |
| elif truth == 0 and pred == 0: |
| tn += 1 |
| elif truth == 0 and pred == 1: |
| fp += 1 |
| elif truth == 1 and pred == 0: |
| fn += 1 |
| return {"tp": tp, "tn": tn, "fp": fp, "fn": fn} |
|
|
|
|
| def _accuracy(tp: int, tn: int, fp: int, fn: int) -> float: |
| denom = tp + tn + fp + fn |
| return (tp + tn) / denom if denom else 0.0 |
|
|
|
|
| def _precision(tp: int, fp: int) -> float: |
| denom = tp + fp |
| return tp / denom if denom else 0.0 |
|
|
|
|
| def _recall(tp: int, fn: int) -> float: |
| denom = tp + fn |
| return tp / denom if denom else 0.0 |
|
|
|
|
| def _f1(precision: float, recall: float) -> float: |
| denom = precision + recall |
| return 2 * precision * recall / denom if denom else 0.0 |
|
|
|
|
| def _trajectory_diagnostics( |
| reference_rows: List[Dict[str, str]], |
| y_true: List[int], |
| y_pred: List[int], |
| ) -> Dict[str, float]: |
| if not reference_rows or "drift_gradient" not in reference_rows[0]: |
| return { |
| "trajectory_positive_support": 0, |
| "recall_trajectory_deterioration_detection": 0.0, |
| "false_stable_trajectory_rate": 0.0, |
| "trajectory_label_alignment_rate": 0.0, |
| } |
|
|
| trajectory_positive_support = 0 |
| trajectory_detected_tp = 0 |
| trajectory_false_stable = 0 |
| trajectory_alignment_hits = 0 |
|
|
| for row, truth, pred in zip(reference_rows, y_true, y_pred): |
| drift_gradient = _safe_float(row.get("drift_gradient", 0.0)) |
| worsening_trajectory = 1 if drift_gradient > 0 else 0 |
|
|
| if worsening_trajectory == 1: |
| trajectory_positive_support += 1 |
| if pred == 1: |
| trajectory_detected_tp += 1 |
| if pred == 0: |
| trajectory_false_stable += 1 |
|
|
| if worsening_trajectory == truth: |
| trajectory_alignment_hits += 1 |
|
|
| recall_trajectory_deterioration_detection = ( |
| trajectory_detected_tp / trajectory_positive_support |
| if trajectory_positive_support |
| else 0.0 |
| ) |
|
|
| false_stable_trajectory_rate = ( |
| trajectory_false_stable / trajectory_positive_support |
| if trajectory_positive_support |
| else 0.0 |
| ) |
|
|
| trajectory_label_alignment_rate = ( |
| trajectory_alignment_hits / len(reference_rows) |
| if reference_rows |
| else 0.0 |
| ) |
|
|
| return { |
| "trajectory_positive_support": trajectory_positive_support, |
| "recall_trajectory_deterioration_detection": recall_trajectory_deterioration_detection, |
| "false_stable_trajectory_rate": false_stable_trajectory_rate, |
| "trajectory_label_alignment_rate": trajectory_label_alignment_rate, |
| } |
|
|
|
|
| def score( |
| reference_path: str = DEFAULT_REFERENCE_PATH, |
| predictions_path: str = DEFAULT_PREDICTIONS_PATH, |
| threshold: float = 0.5, |
| ) -> Dict[str, object]: |
| reference_rows = _read_csv(reference_path) |
| prediction_rows = _read_csv(predictions_path) |
|
|
| if not reference_rows: |
| raise ValueError("Reference file is empty.") |
|
|
| label_col = _find_label_column(list(reference_rows[0].keys())) |
| pred_label_col, pred_score_col = _find_prediction_columns(list(prediction_rows[0].keys())) |
|
|
| y_true, y_pred, y_score, support, matched_reference_rows = _build_y_true_y_pred( |
| reference_rows=reference_rows, |
| prediction_rows=prediction_rows, |
| label_col=label_col, |
| pred_label_col=pred_label_col, |
| pred_score_col=pred_score_col, |
| threshold=threshold, |
| ) |
|
|
| cm = _confusion_matrix(y_true, y_pred) |
| precision = _precision(cm["tp"], cm["fp"]) |
| recall = _recall(cm["tp"], cm["fn"]) |
| accuracy = _accuracy(cm["tp"], cm["tn"], cm["fp"], cm["fn"]) |
| f1 = _f1(precision, recall) |
|
|
| trajectory_metrics = _trajectory_diagnostics( |
| reference_rows=matched_reference_rows, |
| y_true=y_true, |
| y_pred=y_pred, |
| ) |
|
|
| return { |
| "label_column": label_col, |
| "prediction_label_column": pred_label_col, |
| "prediction_score_column": pred_score_col, |
| "primary_metric": "recall_trajectory_deterioration_detection", |
| "secondary_metric": "false_stable_trajectory_rate", |
| "threshold_transparency": { |
| "score_threshold_used": threshold if pred_score_col else None, |
| "threshold_applied_to_score_column": pred_score_col, |
| "predictions_interpreted_as": ( |
| "binary labels from prediction column" |
| if pred_label_col |
| else "binary labels thresholded from score column" |
| ), |
| }, |
| "support": { |
| **support, |
| "positive_label_support": sum(y_true), |
| "negative_label_support": len(y_true) - sum(y_true), |
| "predicted_positive_support": sum(y_pred), |
| "predicted_negative_support": len(y_pred) - sum(y_pred), |
| }, |
| "metrics": { |
| "accuracy": round(accuracy, 4), |
| "precision": round(precision, 4), |
| "recall": round(recall, 4), |
| "f1": round(f1, 4), |
| "recall_trajectory_deterioration_detection": round( |
| trajectory_metrics["recall_trajectory_deterioration_detection"], 4 |
| ), |
| "false_stable_trajectory_rate": round( |
| trajectory_metrics["false_stable_trajectory_rate"], 4 |
| ), |
| "trajectory_label_alignment_rate": round( |
| trajectory_metrics["trajectory_label_alignment_rate"], 4 |
| ), |
| }, |
| "confusion_matrix": cm, |
| "trajectory_support": { |
| "trajectory_positive_support": trajectory_metrics["trajectory_positive_support"], |
| }, |
| } |
|
|
|
|
| if __name__ == "__main__": |
| reference_path = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_REFERENCE_PATH |
| predictions_path = sys.argv[2] if len(sys.argv) > 2 else DEFAULT_PREDICTIONS_PATH |
| threshold = float(sys.argv[3]) if len(sys.argv) > 3 else 0.5 |
|
|
| output = score( |
| reference_path=reference_path, |
| predictions_path=predictions_path, |
| threshold=threshold, |
| ) |
| print(json.dumps(output, indent=2)) |