Upload balanced_accuracy.py
Browse files- balanced_accuracy.py +80 -24
balanced_accuracy.py
CHANGED
|
@@ -1,22 +1,34 @@
|
|
| 1 |
-
# balanced_accuracy.py
|
| 2 |
import numpy as np
|
| 3 |
import evaluate
|
| 4 |
import datasets
|
| 5 |
|
| 6 |
_DESCRIPTION = """
|
| 7 |
Balanced Accuracy for imbalanced classification.
|
| 8 |
-
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
"""
|
| 11 |
|
| 12 |
_KWARGS_DESCRIPTION = """
|
| 13 |
Args:
|
| 14 |
-
predictions: 1D list/array
|
| 15 |
-
|
|
|
|
|
|
|
| 16 |
task: "binary" | "multiclass". (Default: "binary")
|
| 17 |
-
num_classes: int, required for multiclass if labels are not 0..K-1.
|
| 18 |
adjusted: bool, default False. (binary: 2*BA-1; multiclass: (BA-1/K)/(1-1/K))
|
| 19 |
-
zero_division: float, default 0.0. Value used when a denominator is 0.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
Returns:
|
| 21 |
dict: {"balanced_accuracy": float}
|
| 22 |
"""
|
|
@@ -33,6 +45,28 @@ def _safe_div(num, den, zero_div=0.0):
|
|
| 33 |
return out
|
| 34 |
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
class BalancedAccuracy(evaluate.Metric):
|
| 37 |
def _info(self):
|
| 38 |
return evaluate.MetricInfo(
|
|
@@ -41,8 +75,8 @@ class BalancedAccuracy(evaluate.Metric):
|
|
| 41 |
inputs_description=_KWARGS_DESCRIPTION,
|
| 42 |
features=datasets.Features(
|
| 43 |
{
|
| 44 |
-
"predictions": datasets.Value("
|
| 45 |
-
"references": datasets.Value("
|
| 46 |
}
|
| 47 |
),
|
| 48 |
reference_urls=[
|
|
@@ -58,15 +92,28 @@ class BalancedAccuracy(evaluate.Metric):
|
|
| 58 |
num_classes: int | None = None,
|
| 59 |
adjusted: bool = False,
|
| 60 |
zero_division: float = 0.0,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
):
|
| 62 |
y_true = np.asarray(references)
|
| 63 |
-
|
| 64 |
|
| 65 |
-
if
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
if task == "binary":
|
| 69 |
-
|
|
|
|
|
|
|
| 70 |
tp = float(((y_true == 1) & (y_pred == 1)).sum())
|
| 71 |
fn = float(((y_true == 1) & (y_pred == 0)).sum())
|
| 72 |
tn = float(((y_true == 0) & (y_pred == 0)).sum())
|
|
@@ -78,14 +125,23 @@ class BalancedAccuracy(evaluate.Metric):
|
|
| 78 |
ba = 2 * ba - 1 # (BA - 0.5)/0.5
|
| 79 |
return {"balanced_accuracy": float(ba)}
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import numpy as np
|
| 2 |
import evaluate
|
| 3 |
import datasets
|
| 4 |
|
| 5 |
_DESCRIPTION = """
|
| 6 |
Balanced Accuracy for imbalanced classification.
|
| 7 |
+
|
| 8 |
+
Definitions
|
| 9 |
+
- Binary: (TPR + TNR) / 2
|
| 10 |
+
- Multiclass: macro-average of per-class recall
|
| 11 |
+
|
| 12 |
+
Quality-of-life
|
| 13 |
+
- from_probas=True: accept probabilities/logits directly (binary threshold or multiclass argmax)
|
| 14 |
+
- ignore_index: skip unlabeled samples (e.g., -100)
|
| 15 |
+
- adjusted=True: sklearn-style chance correction
|
| 16 |
"""
|
| 17 |
|
| 18 |
_KWARGS_DESCRIPTION = """
|
| 19 |
Args:
|
| 20 |
+
predictions: 1D list/array. Integer labels by default; if from_probas=True, pass probabilities/logits.
|
| 21 |
+
- binary: list[0/1] or list[float] (prob for positive class)
|
| 22 |
+
- multiclass: list[int class_id] or 2D array-like of shape (N, K) with class scores/probs
|
| 23 |
+
references: 1D list/array of integer labels.
|
| 24 |
task: "binary" | "multiclass". (Default: "binary")
|
| 25 |
+
num_classes: int, required for multiclass if labels are not 0..K-1 (optional if from_probas=True and scores provided).
|
| 26 |
adjusted: bool, default False. (binary: 2*BA-1; multiclass: (BA-1/K)/(1-1/K))
|
| 27 |
+
zero_division: float, default 0.0. Value used when a denominator is 0 (e.g., no positives for a class).
|
| 28 |
+
from_probas: bool, default False. If True, `predictions` will be interpreted as probabilities/logits.
|
| 29 |
+
threshold: float, default 0.5. Binary threshold when from_probas=True and predictions are 1D.
|
| 30 |
+
proba_pos_index: int, default 1. If binary and predictions are 2D scores with shape (N, 2), which column is positive.
|
| 31 |
+
ignore_index: int | None, default None. If set, samples whose reference == ignore_index will be skipped.
|
| 32 |
Returns:
|
| 33 |
dict: {"balanced_accuracy": float}
|
| 34 |
"""
|
|
|
|
| 45 |
return out
|
| 46 |
|
| 47 |
|
| 48 |
+
def _to_int_labels_binary(y_pred, from_probas: bool, threshold: float, proba_pos_index: int):
|
| 49 |
+
y_pred = np.asarray(y_pred)
|
| 50 |
+
if from_probas:
|
| 51 |
+
if y_pred.ndim == 1:
|
| 52 |
+
return (y_pred >= threshold).astype(int)
|
| 53 |
+
if y_pred.ndim == 2:
|
| 54 |
+
if y_pred.shape[1] == 2:
|
| 55 |
+
return (y_pred[:, proba_pos_index] >= threshold).astype(int)
|
| 56 |
+
return np.argmax(y_pred, axis=1).astype(int)
|
| 57 |
+
raise ValueError("Binary from_probas expects 1D (prob) or 2D (scores) predictions.")
|
| 58 |
+
return y_pred.astype(int)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _to_int_labels_multiclass(y_pred, from_probas: bool):
|
| 62 |
+
y_pred = np.asarray(y_pred)
|
| 63 |
+
if from_probas:
|
| 64 |
+
if y_pred.ndim != 2:
|
| 65 |
+
raise ValueError("Multiclass with from_probas=True expects 2D scores/probs of shape (N, K).")
|
| 66 |
+
return np.argmax(y_pred, axis=1).astype(int)
|
| 67 |
+
return y_pred.astype(int)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
class BalancedAccuracy(evaluate.Metric):
|
| 71 |
def _info(self):
|
| 72 |
return evaluate.MetricInfo(
|
|
|
|
| 75 |
inputs_description=_KWARGS_DESCRIPTION,
|
| 76 |
features=datasets.Features(
|
| 77 |
{
|
| 78 |
+
"predictions": datasets.Value("float64"),
|
| 79 |
+
"references": datasets.Value("float64"),
|
| 80 |
}
|
| 81 |
),
|
| 82 |
reference_urls=[
|
|
|
|
| 92 |
num_classes: int | None = None,
|
| 93 |
adjusted: bool = False,
|
| 94 |
zero_division: float = 0.0,
|
| 95 |
+
from_probas: bool = False,
|
| 96 |
+
threshold: float = 0.5,
|
| 97 |
+
proba_pos_index: int = 1,
|
| 98 |
+
ignore_index: int | None = None,
|
| 99 |
):
|
| 100 |
y_true = np.asarray(references)
|
| 101 |
+
y_pred_raw = np.asarray(predictions)
|
| 102 |
|
| 103 |
+
if ignore_index is not None:
|
| 104 |
+
mask = y_true != ignore_index
|
| 105 |
+
y_true = y_true[mask]
|
| 106 |
+
y_pred_raw = y_pred_raw[mask]
|
| 107 |
+
if y_true.size == 0:
|
| 108 |
+
return {"balanced_accuracy": float("nan")}
|
| 109 |
+
|
| 110 |
+
if y_true.ndim != 1:
|
| 111 |
+
raise ValueError("`references` must be 1D integer labels, e.g., [0,1,1,0].")
|
| 112 |
|
| 113 |
if task == "binary":
|
| 114 |
+
y_pred = _to_int_labels_binary(y_pred_raw, from_probas, threshold, proba_pos_index)
|
| 115 |
+
y_true = y_true.astype(int)
|
| 116 |
+
|
| 117 |
tp = float(((y_true == 1) & (y_pred == 1)).sum())
|
| 118 |
fn = float(((y_true == 1) & (y_pred == 0)).sum())
|
| 119 |
tn = float(((y_true == 0) & (y_pred == 0)).sum())
|
|
|
|
| 125 |
ba = 2 * ba - 1 # (BA - 0.5)/0.5
|
| 126 |
return {"balanced_accuracy": float(ba)}
|
| 127 |
|
| 128 |
+
if task == "multiclass":
|
| 129 |
+
y_pred = _to_int_labels_multiclass(y_pred_raw, from_probas)
|
| 130 |
+
y_true = y_true.astype(int)
|
| 131 |
+
|
| 132 |
+
if num_classes is None:
|
| 133 |
+
if from_probas and y_pred_raw.ndim == 2:
|
| 134 |
+
num_classes = y_pred_raw.shape[1]
|
| 135 |
+
else:
|
| 136 |
+
num_classes = int(max(y_true.max(), y_pred.max())) + 1
|
| 137 |
+
|
| 138 |
+
tp = np.array([(y_pred[y_true == c] == c).sum() for c in range(num_classes)], dtype=float)
|
| 139 |
+
fn = np.array([(y_pred[y_true == c] != c).sum() for c in range(num_classes)], dtype=float)
|
| 140 |
+
recall_c = _safe_div(tp, tp + fn, zero_division)
|
| 141 |
+
ba = float(recall_c.mean())
|
| 142 |
+
if adjusted:
|
| 143 |
+
chance = 1.0 / float(num_classes)
|
| 144 |
+
ba = float((ba - chance) / (1.0 - chance))
|
| 145 |
+
return {"balanced_accuracy": ba}
|
| 146 |
+
|
| 147 |
+
raise ValueError("`task` must be 'binary' or 'multiclass'.")
|