From d07a9d5734e5c759ea4d290a64fd84aa769d7d2c Mon Sep 17 00:00:00 2001 From: muhmad Date: Sun, 15 Mar 2026 00:02:52 +0100 Subject: [PATCH] Fix confusion_matrix crash on single-class predictions When all labels or predictions are the same class, sklearn's confusion_matrix returns a 1x1 matrix. Unpacking into 4 variables crashes with ValueError. Fix: Pass labels=[0, 1] to force 2x2 matrix, handle empty input, and guard average_precision_score against single-class y_true. Example: y_true = [0, 0, 0, 0], y_pred = [0.1, 0.2, 0.1, 0.3] Before: confusion_matrix -> [[4]] -> ValueError on unpack After: confusion_matrix(labels=[0,1]) -> [[4,0],[0,0]] -> works --- detection/validator/reward.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/detection/validator/reward.py b/detection/validator/reward.py index 6f5e870..4f5053b 100644 --- a/detection/validator/reward.py +++ b/detection/validator/reward.py @@ -36,11 +36,14 @@ def reward(y_pred: np.array, y_true: np.array) -> float: """ preds = np.round(y_pred) - # accuracy = accuracy_score(y_true, preds) - cm = confusion_matrix(y_true, preds) + if len(y_true) == 0: + return 0, {'fp_score': 0, 'f1_score': 0, 'ap_score': 0} + + # Handle single-class case where confusion_matrix returns 1x1 + cm = confusion_matrix(y_true, preds, labels=[0, 1]) tn, fp, fn, tp = cm.ravel() - f1 = f1_score(y_true, preds) - ap_score = average_precision_score(y_true, y_pred) + f1 = f1_score(y_true, preds, zero_division=0) + ap_score = average_precision_score(y_true, y_pred) if len(np.unique(y_true)) > 1 else 0.0 res = {'fp_score': 1 - fp / len(y_pred), 'f1_score': f1,