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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Balanced Accuracy Metrics for 🤗 Evaluate
|
| 2 |
+
|
| 3 |
+
A minimal, production-ready set of **balanced accuracy** metrics for imbalanced vision/NLP tasks, implemented as plain Python scripts that you can load with `evaluate` from a **dataset-type** repo on the Hugging Face Hub.
|
| 4 |
+
|
| 5 |
+
> **What this is**
|
| 6 |
+
>
|
| 7 |
+
> Three drop‑in metrics that focus on fair evaluation under class imbalance:
|
| 8 |
+
>
|
| 9 |
+
> - `balanced_accuracy.py` — **binary & multiclass** balanced accuracy with options for `sample_weight`, `threshold="auto"` (Youden’s J), `ignore_index`, `adjusted`, `class_mask`, `return_per_class`, and `support_per_class`.
|
| 10 |
+
> - `balanced_accuracy_multilabel.py` — **multilabel** balanced accuracy with `average={"macro","weighted","micro"}`, `threshold="auto"` (per label), `sample_weight`, `class_mask`, `ignore_index`, and `support_per_label`.
|
| 11 |
+
> - `balanced_topk_accuracy.py` — **balanced top‑k accuracy** (macro top‑k recall across classes) with `sample_weight`, multiple `k` values, and class masking.
|
| 12 |
+
>
|
| 13 |
+
> **Why it’s useful**
|
| 14 |
+
>
|
| 15 |
+
> - Works without packaging: just download the script and load via `evaluate`.
|
| 16 |
+
> - Designed for long‑tail / imbalanced setups; supports masking, weighting, and chance‑adjustment.
|
| 17 |
+
> - Clear error messages and `reason` fields for edge cases.
|
| 18 |
+
|
| 19 |
+
---
|
| 20 |
+
|
| 21 |
+
## Requirements & Installation
|
| 22 |
+
|
| 23 |
+
Install the minimal dependencies (Python ≥3.9 recommended):
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
pip install --upgrade pip
|
| 27 |
+
pip install evaluate datasets huggingface_hub numpy
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
> **Windows note**: You may see a symlink warning from `huggingface_hub`. It only affects caching and can be ignored. To silence it, set `HF_HUB_DISABLE_SYMLINKS_WARNING=1` or enable Windows Developer Mode.
|
| 31 |
+
|
| 32 |
+
---
|
| 33 |
+
|
| 34 |
+
## Repository Layout
|
| 35 |
+
|
| 36 |
+
This project is intentionally lightweight—each metric is a single Python file living in a dataset‑type Hub repo:
|
| 37 |
+
|
| 38 |
+
```
|
| 39 |
+
balanced_accuracy.py
|
| 40 |
+
balanced_accuracy_multilabel.py
|
| 41 |
+
balanced_topk_accuracy.py
|
| 42 |
+
README.md
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
All three metrics are loadable from the Hub via `hf_hub_download(...)` + `evaluate.load(local_path, module_type="metric")` — no installation step required.
|
| 46 |
+
|
| 47 |
+
---
|
| 48 |
+
|
| 49 |
+
## Quickstart
|
| 50 |
+
|
| 51 |
+
### 0) Common helper
|
| 52 |
+
|
| 53 |
+
```python
|
| 54 |
+
from huggingface_hub import hf_hub_download
|
| 55 |
+
import evaluate
|
| 56 |
+
|
| 57 |
+
REPO = "OliverOnHF/balanced-accuracy" # dataset-type repo
|
| 58 |
+
REV = "main" # or a specific commit hash for reproducibility
|
| 59 |
+
|
| 60 |
+
def load_metric_from_hf(filename):
|
| 61 |
+
path = hf_hub_download(REPO, filename, repo_type="dataset", revision=REV)
|
| 62 |
+
return evaluate.load(path, module_type="metric")
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
### 1) Binary & Multiclass — `balanced_accuracy.py`
|
| 66 |
+
|
| 67 |
+
```python
|
| 68 |
+
m = load_metric_from_hf("balanced_accuracy.py")
|
| 69 |
+
|
| 70 |
+
# Binary (labels)
|
| 71 |
+
print(m.compute(references=[0,1,1,0], predictions=[0,1,0,0], task="binary"))
|
| 72 |
+
# → {'balanced_accuracy': 0.75}
|
| 73 |
+
|
| 74 |
+
# Binary (probabilities) + automatic threshold search (Youden’s J)
|
| 75 |
+
print(m.compute(references=[0,1,1,0],
|
| 76 |
+
predictions=[0.2, 0.9, 0.1, 0.3],
|
| 77 |
+
task="binary", threshold="auto"))
|
| 78 |
+
# → {'balanced_accuracy': 0.75, 'optimal_threshold': 0.6}
|
| 79 |
+
|
| 80 |
+
# Multiclass (macro BA) with per-class recall & sample_weight
|
| 81 |
+
print(m.compute(references=[0,1,2,1],
|
| 82 |
+
predictions=[0,2,2,1],
|
| 83 |
+
task="multiclass", num_classes=3,
|
| 84 |
+
return_per_class=True,
|
| 85 |
+
sample_weight=[1, 0.5, 1, 1]))
|
| 86 |
+
# → {'balanced_accuracy': 0.888888..., 'per_class_recall': [1.0, 0.6666..., 1.0], 'support_per_class': [1.0, 1.5, 1.0]}
|
| 87 |
+
|
| 88 |
+
# Class masking (e.g., tail classes only)
|
| 89 |
+
print(m.compute(references=[0,1,2,1], predictions=[0,2,2,1],
|
| 90 |
+
task="multiclass", num_classes=3,
|
| 91 |
+
class_mask=[1,2], return_per_class=True))
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
**Key arguments**
|
| 95 |
+
|
| 96 |
+
- `task`: `"binary"` or `"multiclass"` (default `"binary"`)
|
| 97 |
+
- `threshold`: float in (0,1) or `"auto"` (binary probabilities only). If predictions are 0/1 labels, threshold is ignored.
|
| 98 |
+
- `num_classes`: for multiclass; inferred if not set (when labels are 0..K‑1).
|
| 99 |
+
- `sample_weight`: per‑sample weights; confusion **counts become weighted sums**.
|
| 100 |
+
- `ignore_index`: skip samples where `reference == ignore_index`.
|
| 101 |
+
- `adjusted`: chance‑corrected BA (`2*BA-1` for binary; `(BA-1/K)/(1-1/K)` for multiclass).
|
| 102 |
+
- `class_mask`: compute macro‑BA over a subset of classes.
|
| 103 |
+
- `return_per_class`: also return per‑class recalls; `support_per_class` is **count or weighted sum** (if `sample_weight` is provided).
|
| 104 |
+
|
| 105 |
+
---
|
| 106 |
+
|
| 107 |
+
### 2) Multilabel — `balanced_accuracy_multilabel.py`
|
| 108 |
+
|
| 109 |
+
```python
|
| 110 |
+
m = load_metric_from_hf("balanced_accuracy_multilabel.py")
|
| 111 |
+
|
| 112 |
+
y_true = [[1,0,1],
|
| 113 |
+
[0,1,0]]
|
| 114 |
+
y_pred = [[1,0,0],
|
| 115 |
+
[0,1,1]]
|
| 116 |
+
|
| 117 |
+
# Labels (0/1)
|
| 118 |
+
print(m.compute(references=y_true, predictions=y_pred, return_per_label=True))
|
| 119 |
+
# → {'balanced_accuracy': 0.6666..., 'per_label_ba': [1.0, 1.0, 0.0], 'support_per_label': [1, 1, 1]}
|
| 120 |
+
|
| 121 |
+
# Probabilities + per-label automatic threshold
|
| 122 |
+
probs = [[0.9,0.2,0.1],
|
| 123 |
+
[0.1,0.8,0.7]]
|
| 124 |
+
print(m.compute(references=y_true, predictions=probs,
|
| 125 |
+
from_probas=True, threshold="auto"))
|
| 126 |
+
# → {'balanced_accuracy': 0.8333..., 'per_label_thresholds': [0.5, 0.5, ~0.7]}
|
| 127 |
+
|
| 128 |
+
# Weighted / micro / class_mask
|
| 129 |
+
print(m.compute(references=y_true, predictions=y_pred,
|
| 130 |
+
average="micro",
|
| 131 |
+
sample_weight=[1.0, 0.5],
|
| 132 |
+
class_mask=[0,2]))
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
**Key arguments**
|
| 136 |
+
|
| 137 |
+
- `from_probas`: if `True`, `predictions` are probabilities in `[0,1]`; else must be 0/1 labels.
|
| 138 |
+
- `threshold`: float in (0,1) or `"auto"` (when `from_probas=True`; `"auto"` selects a threshold per label).
|
| 139 |
+
- `average`: `"macro" | "weighted" | "micro"`
|
| 140 |
+
- *macro*: average BA across labels;
|
| 141 |
+
- *weighted*: weighted by each label’s **positive support**;
|
| 142 |
+
- *micro*: pool TP/TN/FP/FN across all labels then compute BA.
|
| 143 |
+
- `class_mask`: evaluate only the specified label indices.
|
| 144 |
+
- `return_per_label`: additionally return `per_label_ba` and `support_per_label`.
|
| 145 |
+
|
| 146 |
+
---
|
| 147 |
+
|
| 148 |
+
### 3) Balanced Top‑K Accuracy — `balanced_topk_accuracy.py`
|
| 149 |
+
|
| 150 |
+
```python
|
| 151 |
+
import numpy as np
|
| 152 |
+
m = load_metric_from_hf("balanced_topk_accuracy.py")
|
| 153 |
+
|
| 154 |
+
scores = np.array([[0.7, 0.2, 0.1],
|
| 155 |
+
[0.1, 0.3, 0.6],
|
| 156 |
+
[0.05, 0.05,0.9],
|
| 157 |
+
[0.05, 0.9, 0.05]])
|
| 158 |
+
y_true = [0,1,2,1]
|
| 159 |
+
|
| 160 |
+
# top-1 (macro recall across classes)
|
| 161 |
+
print(m.compute(references=y_true, predictions=scores, k=1, return_per_class=True))
|
| 162 |
+
# → {'balanced_topk_accuracy': 0.8333..., 'per_class_recall': [1.0, 0.5, 1.0]}
|
| 163 |
+
|
| 164 |
+
# multiple k at once
|
| 165 |
+
print(m.compute(references=y_true, predictions=scores, k_list=[1,2], return_per_class=True))
|
| 166 |
+
# → {'balanced_topk_accuracy': {1: 0.8333..., 2: 1.0}, 'per_class_recall': {1: [...], 2: [...]}}
|
| 167 |
+
|
| 168 |
+
# with sample_weight and class_mask
|
| 169 |
+
print(m.compute(references=y_true, predictions=scores, k=1,
|
| 170 |
+
sample_weight=[1,0.5,1,1], class_mask=[0,1,2]))
|
| 171 |
+
```
|
| 172 |
+
|
| 173 |
+
**Intuition**: For each class `c`, compute recall@k among samples of class `c`, then macro‑average across classes (optionally over a masked subset).
|
| 174 |
+
|
| 175 |
+
---
|
| 176 |
+
|
| 177 |
+
## Expected Outputs (Sanity Check)
|
| 178 |
+
|
| 179 |
+
These should match what you get locally:
|
| 180 |
+
|
| 181 |
+
```
|
| 182 |
+
# Binary BA
|
| 183 |
+
{'balanced_accuracy': 0.75}
|
| 184 |
+
|
| 185 |
+
# Binary BA with auto threshold (probs: [0.2, 0.9, 0.1, 0.3])
|
| 186 |
+
{'balanced_accuracy': 0.75, 'optimal_threshold': 0.6}
|
| 187 |
+
|
| 188 |
+
# Multiclass BA with weights
|
| 189 |
+
{'balanced_accuracy': 0.888888..., 'per_class_recall': [1.0, 0.6666..., 1.0], 'support_per_class': [1.0, 1.5, 1.0]}
|
| 190 |
+
|
| 191 |
+
# Multilabel BA (labels)
|
| 192 |
+
{'balanced_accuracy': 0.6666..., 'per_label_ba': [1.0, 1.0, 0.0], 'support_per_label': [1, 1, 1]}
|
| 193 |
+
|
| 194 |
+
# Multilabel BA (probs + auto thresholds)
|
| 195 |
+
{'balanced_accuracy': 0.8333..., 'per_label_thresholds': [0.5, 0.5, ~0.7]}
|
| 196 |
+
|
| 197 |
+
# Balanced top-1 and top-2
|
| 198 |
+
{'balanced_topk_accuracy': 0.8333..., 'per_class_recall': [1.0, 0.5, 1.0]}
|
| 199 |
+
{'balanced_topk_accuracy': {1: 0.8333..., 2: 1.0}, 'per_class_recall': {1: [...], 2: [...]}}
|
| 200 |
+
```
|
| 201 |
+
|
| 202 |
+
---
|
| 203 |
+
|
| 204 |
+
## API Reference (TL;DR)
|
| 205 |
+
|
| 206 |
+
### `balanced_accuracy.py` (binary/multiclass)
|
| 207 |
+
|
| 208 |
+
- **Args**:
|
| 209 |
+
`predictions`, `references`, `task={"binary","multiclass"}`, `num_classes=None`,
|
| 210 |
+
`adjusted=False`, `zero_division=0.0`, `threshold=None|"auto" (binary prob)`,
|
| 211 |
+
`ignore_index=None`, `return_per_class=False`, `class_mask=None`, `sample_weight=None`
|
| 212 |
+
- **Returns**:
|
| 213 |
+
`{"balanced_accuracy": float}` + optional `{"optimal_threshold": float}` (binary, auto) +
|
| 214 |
+
optional `{"per_class_recall": list[float], "support_per_class": list[int|float]}` (multiclass).
|
| 215 |
+
|
| 216 |
+
### `balanced_accuracy_multilabel.py`
|
| 217 |
+
|
| 218 |
+
- **Args**:
|
| 219 |
+
`predictions`, `references`, `from_probas=False`, `threshold=0.5|"auto"`,
|
| 220 |
+
`zero_division=0.0`, `average="macro"|"weighted"|"micro"`, `class_mask=None`,
|
| 221 |
+
`ignore_index=None`, `return_per_label=False`, `sample_weight=None`
|
| 222 |
+
- **Returns**:
|
| 223 |
+
`{"balanced_accuracy": float}` + optional `{"per_label_thresholds": list[float]}` (auto) +
|
| 224 |
+
optional `{"per_label_ba": list[float], "support_per_label": list[int]}`.
|
| 225 |
+
|
| 226 |
+
### `balanced_topk_accuracy.py`
|
| 227 |
+
|
| 228 |
+
- **Args**:
|
| 229 |
+
`predictions (N,K)`, `references (N)`, `k=1` or `k_list=[...]`, `class_mask=None`,
|
| 230 |
+
`sample_weight=None`, `zero_division=0.0`, `return_per_class=False`
|
| 231 |
+
- **Returns**:
|
| 232 |
+
`{"balanced_topk_accuracy": float | dict[int,float]}` + optional `{"per_class_recall": ...}`.
|
| 233 |
+
|
| 234 |
+
---
|
| 235 |
+
|
| 236 |
+
## Error Messages & Special Reasons
|
| 237 |
+
|
| 238 |
+
Friendly messages you may encounter by design:
|
| 239 |
+
|
| 240 |
+
- **Length/shape**: “Mismatch in the number of predictions …” / “Multilabel expects 2D arrays …”
|
| 241 |
+
- **NaN/Inf**: “`predictions` contains NaN/Inf.”
|
| 242 |
+
- **Binary**:
|
| 243 |
+
- labels not in {0,1} → “For binary with label predictions, values must be 0/1.”
|
| 244 |
+
- probs not in [0,1] → “For binary with probabilities, `predictions` must be in [0,1].”
|
| 245 |
+
- **Multiclass**: label out of range → “`predictions`/`references` must be in [0,K‑1] …”
|
| 246 |
+
- **Multilabel**: average invalid / prob or label value invalid / shape mismatch
|
| 247 |
+
- **Top‑k**: invalid `k` / label out of range
|
| 248 |
+
- **Reasoned NaN**:
|
| 249 |
+
- `{"reason": "empty_after_ignore_index"}` — all samples were ignored
|
| 250 |
+
- `{"reason": "empty_class_mask_after_filtering"}` — class/label mask removed everything
|
| 251 |
+
|
| 252 |
+
---
|
| 253 |
+
|
| 254 |
+
## Reproducible Smoke Test
|
| 255 |
+
|
| 256 |
+
Copy into `test_all.py` and run:
|
| 257 |
+
|
| 258 |
+
```python
|
| 259 |
+
from huggingface_hub import hf_hub_download
|
| 260 |
+
import evaluate, numpy as np
|
| 261 |
+
|
| 262 |
+
REPO, REV = "OliverOnHF/balanced-accuracy", "main"
|
| 263 |
+
def load(fname): return evaluate.load(hf_hub_download(REPO, fname, repo_type="dataset", revision=REV), module_type="metric")
|
| 264 |
+
|
| 265 |
+
# 1) binary & multiclass
|
| 266 |
+
mba = load("balanced_accuracy.py")
|
| 267 |
+
print(mba.compute(references=[0,1,1,0], predictions=[0,1,0,0], task="binary"))
|
| 268 |
+
print(mba.compute(references=[0,1,1,0], predictions=[0.2,0.9,0.1,0.3], task="binary", threshold="auto"))
|
| 269 |
+
print(mba.compute(references=[0,1,2,1], predictions=[0,2,2,1], task="multiclass", num_classes=3, return_per_class=True, sample_weight=[1,0.5,1,1]))
|
| 270 |
+
|
| 271 |
+
# 2) multilabel
|
| 272 |
+
mml = load("balanced_accuracy_multilabel.py")
|
| 273 |
+
y_true = [[1,0,1],[0,1,0]]; y_pred = [[1,0,0],[0,1,1]]; probs = [[0.9,0.2,0.1],[0.1,0.8,0.7]]
|
| 274 |
+
print(mml.compute(references=y_true, predictions=y_pred, return_per_label=True))
|
| 275 |
+
print(mml.compute(references=y_true, predictions=probs, from_probas=True, threshold="auto"))
|
| 276 |
+
|
| 277 |
+
# 3) top-k
|
| 278 |
+
mtk = load("balanced_topk_accuracy.py")
|
| 279 |
+
scores = np.array([[0.7,0.2,0.1],[0.1,0.3,0.6],[0.05,0.05,0.9],[0.05,0.9,0.05]]); y_true = [0,1,2,1]
|
| 280 |
+
print(mtk.compute(references=y_true, predictions=scores, k=1, return_per_class=True))
|
| 281 |
+
print(mtk.compute(references=y_true, predictions=scores, k_list=[1,2], return_per_class=True))
|
| 282 |
+
```
|
| 283 |
+
|
| 284 |
+
---
|
| 285 |
+
|
| 286 |
+
## Tips
|
| 287 |
+
|
| 288 |
+
- Pin `revision` to a commit hash for exact reproducibility.
|
| 289 |
+
- `support_per_class` / `support_per_label` are **counts** when unweighted; if `sample_weight` is provided they become **effective weight sums** (floats).
|
| 290 |
+
- For extreme long‑tail distributions, combine `class_mask` with per‑class analysis for stable reporting.
|
| 291 |
+
|
| 292 |
+
---
|
| 293 |
+
|
| 294 |
+
## License
|
| 295 |
+
|
| 296 |
+
MIT (suggested). If you need a specific license, add a root `LICENSE` file.
|