OliverOnHF commited on
Commit
ce6f2f3
·
verified ·
1 Parent(s): 6a9f203

Upload balanced_accuracy_multilabel.py

Browse files
Files changed (1) hide show
  1. balanced_accuracy_multilabel.py +85 -0
balanced_accuracy_multilabel.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import evaluate
3
+ import datasets
4
+
5
+ _DESCRIPTION = """
6
+ Multilabel Balanced Accuracy:
7
+ For each label treat it as a binary task and compute BA = (TPR + TNR)/2, then macro-average over labels.
8
+ Supports probability inputs (from_probas=True) with thresholding, and returns per-label BA if requested.
9
+ """
10
+
11
+ _KWARGS_DESCRIPTION = """
12
+ Args:
13
+ predictions: list[list[int or float]] of shape (N, L).
14
+ If from_probas=True, values are probabilities in [0,1]; otherwise 0/1 labels.
15
+ references: list[list[int]] of shape (N, L), 0/1 labels.
16
+ from_probas: bool, default False. If True, binarize predictions with `threshold`.
17
+ threshold: float in (0,1), default 0.5.
18
+ zero_division: float, default 0.0. Used when denominator is 0 (no positives/negatives for a label).
19
+ return_per_label: bool, default False. If True, also return per-label BA list.
20
+ Returns:
21
+ dict: {"balanced_accuracy": float, optional "per_label_ba": list[float]}
22
+ """
23
+
24
+ _CITATION = ""
25
+
26
+
27
+ def _safe_div(num, den, zero_div=0.0):
28
+ num = np.asarray(num, dtype=float)
29
+ den = np.asarray(den, dtype=float)
30
+ out = np.full_like(num, float(zero_div))
31
+ mask = den != 0
32
+ out[mask] = num[mask] / den[mask]
33
+ return out
34
+
35
+
36
+ class BalancedAccuracyMultilabel(evaluate.Metric):
37
+ def _info(self):
38
+ return evaluate.MetricInfo(
39
+ description=_DESCRIPTION,
40
+ citation=_CITATION,
41
+ inputs_description=_KWARGS_DESCRIPTION,
42
+ features=datasets.Features(
43
+ {
44
+ "predictions": datasets.Sequence(datasets.Value("float64")),
45
+ "references": datasets.Sequence(datasets.Value("int64")),
46
+ }
47
+ ),
48
+ )
49
+
50
+ def _compute(
51
+ self,
52
+ predictions,
53
+ references,
54
+ from_probas: bool = False,
55
+ threshold: float = 0.5,
56
+ zero_division: float = 0.0,
57
+ return_per_label: bool = False,
58
+ ):
59
+ y_true = np.asarray(references, dtype=int)
60
+ y_pred_in = np.asarray(predictions, dtype=float)
61
+
62
+ if y_true.ndim != 2 or y_pred_in.ndim != 2:
63
+ raise ValueError("Multilabel expects 2D arrays of shape (N, L).")
64
+ if y_true.shape != y_pred_in.shape:
65
+ raise ValueError(f"Shape mismatch: references {y_true.shape} vs predictions {y_pred_in.shape}.")
66
+
67
+ y_pred = (y_pred_in >= threshold).astype(int) if from_probas else y_pred_in.astype(int)
68
+
69
+ L = y_true.shape[1]
70
+ per_label_ba = []
71
+ for j in range(L):
72
+ yt, yp = y_true[:, j], y_pred[:, j]
73
+ tp = float(((yt == 1) & (yp == 1)).sum())
74
+ fn = float(((yt == 1) & (yp == 0)).sum())
75
+ tn = float(((yt == 0) & (yp == 0)).sum())
76
+ fp = float(((yt == 0) & (yp == 1)).sum())
77
+ tpr = _safe_div(tp, tp + fn, zero_division)
78
+ tnr = _safe_div(tn, tn + fp, zero_division)
79
+ per_label_ba.append(0.5 * (tpr + tnr))
80
+
81
+ ba = float(np.mean(per_label_ba)) if L > 0 else float("nan")
82
+ out = {"balanced_accuracy": ba}
83
+ if return_per_label:
84
+ out["per_label_ba"] = per_label_ba
85
+ return out