OliverOnHF commited on
Commit
cbde7fb
·
verified ·
1 Parent(s): 37697b5

Rename balanced-accuracy.py to balanced_accuracy.py

Browse files
balanced-accuracy.py → balanced_accuracy.py RENAMED
@@ -1,78 +1,77 @@
1
- # Balanced Accuracy metric (binary / multiclass / multilabel) for 🤗 Evaluate
2
- import numpy as np
3
- from evaluate import Metric
4
-
5
-
6
- def _safe_div(num, den, zero_div=0.0):
7
- num = np.asarray(num, dtype=float)
8
- den = np.asarray(den, dtype=float)
9
- out = np.full_like(num, fill_value=float(zero_div))
10
- mask = den != 0
11
- out[mask] = num[mask] / den[mask]
12
- return out
13
-
14
-
15
- class BalancedAccuracy(Metric):
16
- def _info(self):
17
- # 不强制声明复杂的 features,保持通用输入
18
- return self._metric_info_from_module(
19
- description=(
20
- "Balanced Accuracy for imbalanced classification.\n"
21
- "Binary: (TPR + TNR) / 2.\n"
22
- "Multiclass: macro-average of per-class recall.\n"
23
- "Multilabel: macro-average of per-label BA."
24
- )
25
- )
26
-
27
- def _compute(
28
- self,
29
- predictions,
30
- references,
31
- task: str = "binary", # "binary" | "multiclass" | "multilabel"
32
- num_classes: int | None = None,
33
- adjusted: bool = False, # sklearn 风格校正
34
- zero_division: float = 0.0, # 分母为 0 的处理
35
- ):
36
- y_true = np.asarray(references)
37
- y_pred = np.asarray(predictions)
38
-
39
- if task == "binary":
40
- # 约定标签 {0,1}
41
- tp = float(((y_true == 1) & (y_pred == 1)).sum())
42
- fn = float(((y_true == 1) & (y_pred == 0)).sum())
43
- tn = float(((y_true == 0) & (y_pred == 0)).sum())
44
- fp = float(((y_true == 0) & (y_pred == 1)).sum())
45
- tpr = _safe_div(tp, tp + fn, zero_division)
46
- tnr = _safe_div(tn, tn + fp, zero_division)
47
- ba = 0.5 * (tpr + tnr)
48
- if adjusted:
49
- ba = 2 * ba - 1 # (BA - 0.5)/0.5
50
- return {"balanced_accuracy": float(ba)}
51
-
52
- if task == "multiclass":
53
- if num_classes is None:
54
- num_classes = int(max(y_true.max(), y_pred.max())) + 1
55
- tp = np.array([(y_pred[y_true == c] == c).sum() for c in range(num_classes)], dtype=float)
56
- fn = np.array([(y_pred[y_true == c] != c).sum() for c in range(num_classes)], dtype=float)
57
- recall_c = _safe_div(tp, tp + fn, zero_division) # per-class recall
58
- ba = float(recall_c.mean())
59
- if adjusted:
60
- chance = 1.0 / float(num_classes)
61
- ba = float((ba - chance) / (1.0 - chance))
62
- return {"balanced_accuracy": ba}
63
-
64
- # multilabel: y_true/y_pred shape: (N, L) with {0,1}
65
- if y_true.ndim != 2:
66
- raise ValueError("For task='multilabel', y_true/y_pred must be 2D arrays of shape (N, L).")
67
- L = y_true.shape[1]
68
- per_label = []
69
- for j in range(L):
70
- yt, yp = y_true[:, j], y_pred[:, j]
71
- tp = float(((yt == 1) & (yp == 1)).sum())
72
- fn = float(((yt == 1) & (yp == 0)).sum())
73
- tn = float(((yt == 0) & (yp == 0)).sum())
74
- fp = float(((yt == 0) & (yp == 1)).sum())
75
- tpr = _safe_div(tp, tp + fn, zero_division)
76
- tnr = _safe_div(tn, tn + fp, zero_division)
77
- per_label.append(0.5 * (tpr + tnr))
78
- return {"balanced_accuracy": float(np.mean(per_label))}
 
1
+ # Balanced Accuracy metric (binary / multiclass / multilabel) for 🤗 Evaluate
2
+ import numpy as np
3
+ from evaluate import Metric
4
+
5
+
6
+ def _safe_div(num, den, zero_div=0.0):
7
+ num = np.asarray(num, dtype=float)
8
+ den = np.asarray(den, dtype=float)
9
+ out = np.full_like(num, fill_value=float(zero_div))
10
+ mask = den != 0
11
+ out[mask] = num[mask] / den[mask]
12
+ return out
13
+
14
+
15
+ class BalancedAccuracy(Metric):
16
+ def _info(self):
17
+ return self._metric_info_from_module(
18
+ description=(
19
+ "Balanced Accuracy for imbalanced classification.\n"
20
+ "Binary: (TPR + TNR) / 2.\n"
21
+ "Multiclass: macro-average of per-class recall.\n"
22
+ "Multilabel: macro-average of per-label BA."
23
+ )
24
+ )
25
+
26
+ def _compute(
27
+ self,
28
+ predictions,
29
+ references,
30
+ task: str = "binary", # "binary" | "multiclass" | "multilabel"
31
+ num_classes: int | None = None,
32
+ adjusted: bool = False,
33
+ zero_division: float = 0.0,
34
+ ):
35
+ y_true = np.asarray(references)
36
+ y_pred = np.asarray(predictions)
37
+
38
+ if task == "binary":
39
+ # 约定标签 {0,1}
40
+ tp = float(((y_true == 1) & (y_pred == 1)).sum())
41
+ fn = float(((y_true == 1) & (y_pred == 0)).sum())
42
+ tn = float(((y_true == 0) & (y_pred == 0)).sum())
43
+ fp = float(((y_true == 0) & (y_pred == 1)).sum())
44
+ tpr = _safe_div(tp, tp + fn, zero_division)
45
+ tnr = _safe_div(tn, tn + fp, zero_division)
46
+ ba = 0.5 * (tpr + tnr)
47
+ if adjusted:
48
+ ba = 2 * ba - 1 # (BA - 0.5)/0.5
49
+ return {"balanced_accuracy": float(ba)}
50
+
51
+ if task == "multiclass":
52
+ if num_classes is None:
53
+ num_classes = int(max(y_true.max(), y_pred.max())) + 1
54
+ tp = np.array([(y_pred[y_true == c] == c).sum() for c in range(num_classes)], dtype=float)
55
+ fn = np.array([(y_pred[y_true == c] != c).sum() for c in range(num_classes)], dtype=float)
56
+ recall_c = _safe_div(tp, tp + fn, zero_division) # per-class recall
57
+ ba = float(recall_c.mean())
58
+ if adjusted:
59
+ chance = 1.0 / float(num_classes)
60
+ ba = float((ba - chance) / (1.0 - chance))
61
+ return {"balanced_accuracy": ba}
62
+
63
+ # multilabel: y_true/y_pred shape: (N, L) with {0,1}
64
+ if y_true.ndim != 2:
65
+ raise ValueError("For task='multilabel', y_true/y_pred must be 2D arrays of shape (N, L).")
66
+ L = y_true.shape[1]
67
+ per_label = []
68
+ for j in range(L):
69
+ yt, yp = y_true[:, j], y_pred[:, j]
70
+ tp = float(((yt == 1) & (yp == 1)).sum())
71
+ fn = float(((yt == 1) & (yp == 0)).sum())
72
+ tn = float(((yt == 0) & (yp == 0)).sum())
73
+ fp = float(((yt == 0) & (yp == 1)).sum())
74
+ tpr = _safe_div(tp, tp + fn, zero_division)
75
+ tnr = _safe_div(tn, tn + fp, zero_division)
76
+ per_label.append(0.5 * (tpr + tnr))
77
+ return {"balanced_accuracy": float(np.mean(per_label))}