LNPBench / code /src /lnpbench /metrics.py
eduzrh's picture
LNPBench: code, caches, results and figures
d1988f5 verified
Raw History Blame Contribute Delete
3.07 kB
"""Evaluation metrics used throughout the benchmark."""
from __future__ import annotations
from typing import Dict
import numpy as np
from scipy import stats
def spearman(y_true: np.ndarray, y_pred: np.ndarray) -> float:
if len(y_true) < 3 or np.std(y_true) == 0 or np.std(y_pred) == 0:
return float("nan")
return float(stats.spearmanr(y_true, y_pred).statistic)
def pearson(y_true: np.ndarray, y_pred: np.ndarray) -> float:
if len(y_true) < 3 or np.std(y_true) == 0 or np.std(y_pred) == 0:
return float("nan")
return float(stats.pearsonr(y_true, y_pred)[0])
def r2(y_true: np.ndarray, y_pred: np.ndarray) -> float:
ss_res = float(((y_true - y_pred) ** 2).sum())
ss_tot = float(((y_true - y_true.mean()) ** 2).sum())
return 1.0 - ss_res / (ss_tot + 1e-12)
def mae(y_true: np.ndarray, y_pred: np.ndarray) -> float:
return float(np.mean(np.abs(y_true - y_pred)))
def rmse(y_true: np.ndarray, y_pred: np.ndarray) -> float:
return float(np.sqrt(np.mean((y_true - y_pred) ** 2)))
def top_k_recall(y_true: np.ndarray, y_pred: np.ndarray, k: int) -> float:
"""Overlap between the predicted top-k and the true top-k (random = k/n)."""
n = len(y_true)
k = max(1, min(k, n))
true_top = set(np.argsort(-y_true)[:k].tolist())
pred_top = set(np.argsort(-y_pred)[:k].tolist())
return len(true_top & pred_top) / k
def enrichment_factor(y_true: np.ndarray, y_pred: np.ndarray, frac: float = 0.1) -> float:
n = len(y_true)
k = max(1, int(round(frac * n)))
return top_k_recall(y_true, y_pred, k) / (k / n)
def ndcg_at_k(y_true: np.ndarray, y_pred: np.ndarray, frac: float = 0.1) -> float:
n = len(y_true)
k = max(1, int(round(frac * n)))
order = np.argsort(-y_pred)[:k]
gains = y_true[order] - y_true.min()
disc = 1.0 / np.log2(np.arange(2, k + 2))
dcg = float((gains * disc).sum())
ideal = np.sort(y_true - y_true.min())[::-1][:k]
idcg = float((ideal * disc).sum())
return dcg / idcg if idcg > 0 else float("nan")
def evaluate(y_true: np.ndarray, y_pred: np.ndarray) -> Dict[str, float]:
y_true = np.asarray(y_true, dtype=float)
y_pred = np.asarray(y_pred, dtype=float)
return {
"spearman": spearman(y_true, y_pred),
"pearson": pearson(y_true, y_pred),
"r2": r2(y_true, y_pred),
"mae": mae(y_true, y_pred),
"rmse": rmse(y_true, y_pred),
"ef10": enrichment_factor(y_true, y_pred, 0.10),
"ef20": enrichment_factor(y_true, y_pred, 0.20),
"ndcg10": ndcg_at_k(y_true, y_pred, 0.10),
}
def bootstrap_ci(y_true: np.ndarray, y_pred: np.ndarray, metric=spearman, n_boot: int = 1000, seed: int = 0):
rng = np.random.default_rng(seed)
n = len(y_true)
vals = []
for _ in range(n_boot):
idx = rng.integers(0, n, n)
v = metric(y_true[idx], y_pred[idx])
if np.isfinite(v):
vals.append(v)
if not vals:
return float("nan"), float("nan")
return float(np.percentile(vals, 2.5)), float(np.percentile(vals, 97.5))