lsv / lsvbench /metrics.py
smerkd's picture
Initial commit
f91d9a0 verified
Raw
History Blame Contribute Delete
3.78 kB
"""Generic metric helpers for benchmark tasks."""
from __future__ import annotations
import random
import statistics
from collections import Counter
from typing import Any, Callable, Iterable
def safe_div(num: float, denom: float) -> float | None:
return num / denom if denom else None
def mean(values: Iterable[float | None]) -> float | None:
clean = [value for value in values if value is not None]
return sum(clean) / len(clean) if clean else None
def classification_scores(
pairs: Iterable[tuple[Any, Any]],
*,
labels: Iterable[Any] | None = None,
none_is_wrong: bool = True,
) -> dict[str, Any]:
"""Compute accuracy, balanced accuracy, F1, precision, recall, and confusion."""
pair_list = list(pairs)
if labels is None:
label_values = sorted(
{
str(value)
for target, pred in pair_list
for value in (target, pred)
if value is not None
}
)
else:
label_values = [str(label) for label in labels]
total = len(pair_list)
correct = sum(1 for target, pred in pair_list if pred is not None and str(target) == str(pred))
target_total: Counter[str] = Counter()
pred_total: Counter[str] = Counter()
class_correct: Counter[str] = Counter()
confusion: Counter[str] = Counter()
for target, pred in pair_list:
target_s = str(target)
pred_s = "UNPARSED" if pred is None and none_is_wrong else str(pred)
target_total[target_s] += 1
pred_total[pred_s] += 1
confusion[f"{target_s}->{pred_s}"] += 1
if target_s == pred_s:
class_correct[target_s] += 1
recall: dict[str, float] = {}
precision: dict[str, float] = {}
f1: dict[str, float] = {}
for label in label_values:
recall[label] = class_correct[label] / target_total[label] if target_total[label] else 0.0
precision[label] = class_correct[label] / pred_total[label] if pred_total[label] else 0.0
denom = precision[label] + recall[label]
f1[label] = 2 * precision[label] * recall[label] / denom if denom else 0.0
return {
"accuracy": correct / total if total else None,
"balanced_accuracy": mean(recall.values()) if total and label_values else None,
"macro_f1": mean(f1.values()) if total and label_values else None,
"macro_precision": mean(precision.values()) if total and label_values else None,
"macro_recall": mean(recall.values()) if total and label_values else None,
"precision": precision,
"recall": recall,
"f1": f1,
"confusion": dict(confusion),
"target_counts": dict(target_total),
"pred_counts": dict(pred_total),
}
def parse_success_rate(rows: list[dict[str, Any]], field: str = "pred_parse_ok") -> float | None:
if not rows:
return None
return sum(1 for row in rows if row.get(field)) / len(rows)
def metric_value(summary: dict[str, Any], metric: str) -> float | None:
value = summary.get(metric)
return value if isinstance(value, (int, float)) else None
def bootstrap_sem(
rows: list[dict[str, Any]],
metric: str,
summarize_fn: Callable[[list[dict[str, Any]]], dict[str, Any]],
*,
iterations: int = 500,
seed: int = 17,
) -> float | None:
if not rows:
return None
rng = random.Random(f"{seed}:{metric}:{len(rows)}")
values: list[float] = []
for _ in range(iterations):
sample = [rows[rng.randrange(len(rows))] for _ in rows]
value = metric_value(summarize_fn(sample), metric)
if value is not None:
values.append(value)
if not values:
return None
return statistics.stdev(values) if len(values) > 1 else 0.0