| import pandas as pd |
| from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix |
|
|
|
|
| def _resolve_target_col(df: pd.DataFrame) -> str: |
| label_cols = [c for c in df.columns if c.startswith("label_")] |
| if len(label_cols) == 1: |
| return label_cols[0] |
|
|
| raise ValueError( |
| f"Expected exactly one label column starting with 'label_', found: {label_cols}" |
| ) |
|
|
|
|
| def score(solution, submission): |
| if isinstance(solution, str): |
| solution = pd.read_csv(solution) |
|
|
| if isinstance(submission, str): |
| submission = pd.read_csv(submission) |
|
|
| target_col = _resolve_target_col(solution) |
|
|
| if target_col not in submission.columns: |
| submission_label_cols = [c for c in submission.columns if c.startswith("label_")] |
| if len(submission_label_cols) == 1: |
| submission = submission.rename(columns={submission_label_cols[0]: target_col}) |
| else: |
| raise ValueError( |
| f"Submission must contain target column '{target_col}' or exactly one label column. " |
| f"Found: {list(submission.columns)}" |
| ) |
|
|
| y_true = solution[target_col] |
| y_pred = submission[target_col] |
|
|
| accuracy = accuracy_score(y_true, y_pred) |
| precision = precision_score(y_true, y_pred, zero_division=0) |
| recall = recall_score(y_true, y_pred, zero_division=0) |
| f1 = f1_score(y_true, y_pred, zero_division=0) |
| cm = confusion_matrix(y_true, y_pred) |
|
|
| return { |
| "target_column": target_col, |
| "positive_class": 1, |
| "primary_metric": "recall_cascade_detection", |
| "accuracy": accuracy, |
| "precision": precision, |
| "recall_cascade_detection": recall, |
| "false_safe_rate": 1 - recall, |
| "f1": f1, |
| "confusion_matrix": cm.tolist(), |
| } |