File size: 3,070 Bytes
d1988f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""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))