"""M1+ metrics with explicit fixed and validation-calibrated operating points.""" import numpy as np from sklearn.metrics import confusion_matrix, roc_auc_score, roc_curve, average_precision_score, brier_score_loss, matthews_corrcoef def binary(y, scores, threshold): y = np.asarray(y, dtype=np.int64) scores = np.asarray(scores, dtype=float) if not len(y) or not np.isfinite(scores).all() or (not np.isin(y, [0, 1]).all()): raise ValueError('Invalid binary evaluation inputs') pred = (scores >= threshold).astype(int) (tn, fp, fn, tp) = map(int, confusion_matrix(y, pred, labels=[0, 1]).ravel()) pod = tp / (tp + fn) if tp + fn else 0.0 pofd = fp / (fp + tn) if fp + tn else 0.0 den = (tp + fn) * (fn + tn) + (tp + fp) * (fp + tn) return {'tss': pod - pofd, 'hss': 2 * (tp * tn - fp * fn) / den if den else 0.0, 'f1': 2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0.0, 'accuracy': (tp + tn) / len(y), 'roc_auc': float(roc_auc_score(y, scores)) if len(np.unique(y)) == 2 else None, 'precision': tp / (tp + fp) if tp + fp else 0.0, 'recall': pod, 'pod': pod, 'far': fp / (tp + fp) if tp + fp else 0.0, 'false_positive_rate': pofd, 'mcc': float(matthews_corrcoef(y, pred)), 'brier': float(brier_score_loss(y, scores)), 'average_precision': float(average_precision_score(y, scores)) if y.sum() else None, 'tn': tn, 'fp': fp, 'fn': fn, 'tp': tp, 'positive_support': tp + fn, 'negative_support': tn + fp} def calibrated_threshold(y, scores): y = np.asarray(y, dtype=int) scores = np.asarray(scores, dtype=float) if len(np.unique(y)) != 2: raise ValueError('Validation threshold selection requires both classes') (fpr, tpr, thresholds) = roc_curve(y, scores, drop_intermediate=False) candidates = [(float(a - b), float(t)) for (a, b, t) in zip(tpr, fpr, thresholds) if np.isfinite(t)] candidates += [(binary(y, scores, 0.5)['tss'], 0.5), (0.0, float(np.nextafter(scores.max(), np.inf))), (0.0, 0.0)] best = max((x[0] for x in candidates)) ties = [t for (value, t) in candidates if abs(value - best) <= 1e-12] chosen = min(ties, key=lambda t: (abs(t - 0.5), -t)) if abs(binary(y, scores, chosen)['tss'] - best) > 1e-10: raise AssertionError('Threshold operating point inconsistent') return chosen