financial-risk-api / src /models /evaluator.py
octavioloffaro's picture
Deploy financial risk API to Hugging Face
bc308f6
Raw History Blame Contribute Delete
3.41 kB
import numpy as np
from sklearn.metrics import roc_auc_score, precision_recall_curve, f1_score, brier_score_loss, auc
from scipy.stats import ks_2samp
def compute_ece(y_true, y_prob, n_bins=10):
"""Computes Expected Calibration Error (ECE) and returns calibration bin details.
ECE partitions predictions into equally spaced bins and calculates the weighted
average of the absolute difference between predicted confidence and empirical accuracy.
"""
y_true = np.array(y_true)
y_prob = np.array(y_prob)
bin_boundaries = np.linspace(0, 1, n_bins + 1)
ece = 0.0
bin_details = []
for i in range(n_bins):
bin_lower = bin_boundaries[i]
bin_upper = bin_boundaries[i + 1]
# Determine elements in this bin
in_bin = (y_prob >= bin_lower) & (y_prob < bin_upper)
if i == n_bins - 1:
in_bin = in_bin | (y_prob == bin_upper)
weight = np.mean(in_bin)
if weight > 0:
accuracy_in_bin = np.mean(y_true[in_bin])
confidence_in_bin = np.mean(y_prob[in_bin])
ece += weight * np.abs(confidence_in_bin - accuracy_in_bin)
bin_details.append({
"bin": f"{bin_lower:.1f}-{bin_upper:.1f}",
"count": int(np.sum(in_bin)),
"actual_rate": float(accuracy_in_bin),
"predicted_prob": float(confidence_in_bin)
})
return float(ece), bin_details
def compute_evaluation_metrics(y_true, y_prob):
"""Computes standard evaluation metrics for probability prediction.
Args:
y_true (array-like): Binary ground truth labels
y_prob (array-like): Predicted probability estimates
Returns:
dict: Evaluation metrics including ROC-AUC, PR-AUC, F1, Brier, KS, and ECE
"""
y_true = np.array(y_true)
y_prob = np.array(y_prob)
if len(y_true) == 0 or len(np.unique(y_true)) < 2:
return {
"roc_auc": 0.5,
"pr_auc": 0.0,
"f1_score": 0.0,
"brier_score": 0.0,
"ks_statistic": 0.0,
"ece": 0.0,
"calibration_bins": [],
"message": "Insufficient class diversity to compute full metrics."
}
# ROC-AUC
roc_auc = roc_auc_score(y_true, y_prob)
# PR-AUC
precisions, recalls, thresholds = precision_recall_curve(y_true, y_prob)
pr_auc = auc(recalls, precisions)
# Best F1 search
f1_scores = []
for t in np.linspace(0.05, 0.95, 19):
y_pred = (y_prob >= t).astype(int)
f1_scores.append(f1_score(y_true, y_pred, zero_division=0))
best_f1 = max(f1_scores) if len(f1_scores) > 0 else 0.0
# Brier Score
brier = brier_score_loss(y_true, y_prob)
# KS Statistic
prob_pos = y_prob[y_true == 1]
prob_neg = y_prob[y_true == 0]
if len(prob_pos) > 0 and len(prob_neg) > 0:
ks_stat, _ = ks_2samp(prob_pos, prob_neg)
else:
ks_stat = 0.0
# Expected Calibration Error
ece, bin_details = compute_ece(y_true, y_prob)
return {
"roc_auc": float(roc_auc),
"pr_auc": float(pr_auc),
"f1_score": float(best_f1),
"brier_score": float(brier),
"ks_statistic": float(ks_stat),
"ece": ece,
"calibration_bins": bin_details
}