| import argparse |
| import json |
| import sys |
| from datetime import datetime, timezone |
|
|
| import pandas as pd |
| from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix |
|
|
|
|
| SCORER_VERSION = "1.2.0" |
|
|
|
|
| def validate_columns(df, required, name): |
| missing = [c for c in required if c not in df.columns] |
| if missing: |
| raise ValueError(f"{name} missing required columns: {missing}") |
|
|
|
|
| def validate_no_duplicates(df, column, name): |
| dupes = df[df[column].duplicated()][column].tolist() |
| if dupes: |
| raise ValueError(f"{name} contains duplicate {column} values: {dupes}") |
|
|
|
|
| def validate_binary_column(df, column, name): |
| invalid = df[~df[column].isin([0, 1])] |
| if not invalid.empty: |
| bad = invalid[["scenario_id", column]].to_dict(orient="records") |
| raise ValueError(f"{name} has non-binary values in {column}: {bad}") |
|
|
|
|
| def dataset_integrity_report(truth): |
| feature_cols = [ |
| c for c in truth.columns |
| if c not in ["scenario_id", "label"] |
| and pd.api.types.is_numeric_dtype(truth[c]) |
| ] |
|
|
| label_counts = truth["label"].value_counts().to_dict() |
| total = len(truth) |
|
|
| label_balance = { |
| "label_0": int(label_counts.get(0, 0)), |
| "label_1": int(label_counts.get(1, 0)), |
| "positive_rate": float(label_counts.get(1, 0) / total) if total else 0.0, |
| } |
|
|
| correlations = {} |
|
|
| for col in feature_cols: |
| corr = truth[col].corr(truth["label"]) |
| if pd.isna(corr): |
| corr = 0.0 |
| correlations[col] = float(corr) |
|
|
| high_correlation_features = { |
| col: corr |
| for col, corr in correlations.items() |
| if abs(corr) >= 0.30 |
| } |
|
|
| return { |
| "num_rows": int(total), |
| "num_features_checked": int(len(feature_cols)), |
| "label_balance": label_balance, |
| "max_abs_feature_label_correlation": float( |
| max([abs(v) for v in correlations.values()], default=0.0) |
| ), |
| "high_correlation_features_abs_ge_0_30": high_correlation_features, |
| "passes_basic_integrity_check": ( |
| 0.35 <= label_balance["positive_rate"] <= 0.65 |
| and len(high_correlation_features) == 0 |
| ), |
| } |
|
|
|
|
| def run_scoring(predictions_path, truth_path): |
| pred = pd.read_csv(predictions_path) |
| truth = pd.read_csv(truth_path) |
|
|
| validate_columns(pred, ["scenario_id", "prediction"], "predictions") |
| validate_columns(truth, ["scenario_id", "label"], "truth") |
|
|
| validate_no_duplicates(pred, "scenario_id", "predictions") |
| validate_no_duplicates(truth, "scenario_id", "truth") |
|
|
| validate_binary_column(pred, "prediction", "predictions") |
| validate_binary_column(truth, "label", "truth") |
|
|
| merged = truth[["scenario_id", "label"]].merge( |
| pred[["scenario_id", "prediction"]], |
| on="scenario_id", |
| how="left", |
| indicator=True, |
| ) |
|
|
| missing = merged[merged["_merge"] == "left_only"]["scenario_id"].tolist() |
| if missing: |
| raise ValueError(f"Missing predictions for scenario_id: {missing}") |
|
|
| extra = pred[~pred["scenario_id"].isin(truth["scenario_id"])]["scenario_id"].tolist() |
| if extra: |
| raise ValueError(f"Predictions contain unknown scenario_id: {extra}") |
|
|
| y_true = merged["label"].astype(int) |
| y_pred = merged["prediction"].astype(int) |
|
|
| metrics = { |
| "scorer_version": SCORER_VERSION, |
| "timestamp_utc": datetime.now(timezone.utc).isoformat(), |
| "num_examples": int(len(merged)), |
| "accuracy": float(accuracy_score(y_true, y_pred)), |
| "precision": float(precision_score(y_true, y_pred, zero_division=0)), |
| "recall": float(recall_score(y_true, y_pred, zero_division=0)), |
| "f1": float(f1_score(y_true, y_pred, zero_division=0)), |
| "confusion_matrix": { |
| "labels": [0, 1], |
| "matrix": confusion_matrix(y_true, y_pred, labels=[0, 1]).tolist(), |
| }, |
| "dataset_integrity": dataset_integrity_report(truth), |
| } |
|
|
| return metrics |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser( |
| description="ClarusC64 binary prediction scorer with dataset integrity checks" |
| ) |
|
|
| parser.add_argument( |
| "--predictions", |
| required=True, |
| help="CSV file with scenario_id,prediction", |
| ) |
|
|
| parser.add_argument( |
| "--truth", |
| default="data/test.csv", |
| help="Truth CSV with scenario_id,label. Default: data/test.csv", |
| ) |
|
|
| parser.add_argument( |
| "--output", |
| default="metrics.json", |
| help="Output JSON file. Default: metrics.json", |
| ) |
|
|
| args = parser.parse_args() |
|
|
| try: |
| metrics = run_scoring(args.predictions, args.truth) |
|
|
| with open(args.output, "w", encoding="utf-8") as f: |
| json.dump(metrics, f, indent=2) |
|
|
| print(json.dumps(metrics, indent=2)) |
| sys.exit(0) |
|
|
| except Exception as e: |
| error = { |
| "scorer_version": SCORER_VERSION, |
| "status": "error", |
| "message": str(e), |
| } |
|
|
| print(json.dumps(error, indent=2), file=sys.stderr) |
| sys.exit(1) |
|
|
|
|
| if __name__ == "__main__": |
| main() |