Skip to content

tgb_mrr_hits

tgb_mrr_hits(
    y_pred_pos: ArrayLike, y_pred_neg: ArrayLike, k: int = 10
) -> tuple[float, float]

MRR and Hits@k of positive scores ranked against their negative scores, as TGB.

The rank of a positive is 1 + (#negatives scoring higher + #negatives scoring at least as high) / 2: a positive tied with m negatives gets the average of its best (first) and worst (last) possible ranks among them, as TGB (and OGB). The reciprocal ranks and the hits are float32 and averaged in float32, as TGB with NumPy inputs.

Parameters:

Name Type Description Default
y_pred_pos ArrayLike

Score of each positive edge, shape [num_pos]

required
y_pred_neg ArrayLike

Scores of the negative edges of each positive, shape [num_pos, num_neg] (or [num_neg] for a single positive). Positives with fewer negatives can be padded with -inf, which never ranks above a (finite) positive score.

required
k int

The k of Hits@k. Default: 10

10

Returns:

Type Description
tuple[float, float]

The mean reciprocal rank and the Hits@k.

Source code in mlx_graphs/metrics/tgb.py
def tgb_mrr_hits(
    y_pred_pos: ArrayLike, y_pred_neg: ArrayLike, k: int = 10
) -> tuple[float, float]:
    r"""MRR and Hits@k of positive scores ranked against their negative scores,
    as TGB.

    The rank of a positive is ``1 + (#negatives scoring higher + #negatives
    scoring at least as high) / 2``: a positive tied with ``m`` negatives gets
    the average of its best (first) and worst (last) possible ranks among them,
    as TGB (and OGB). The reciprocal ranks and the hits are float32 and
    averaged in float32, as TGB with NumPy inputs.

    Args:
        y_pred_pos: Score of each positive edge, shape `[num_pos]`
        y_pred_neg: Scores of the negative edges of each positive, shape
            `[num_pos, num_neg]` (or `[num_neg]` for a single positive).
            Positives with fewer negatives can be padded with ``-inf``, which
            never ranks above a (finite) positive score.
        k: The ``k`` of Hits@k. Default: ``10``

    Returns:
        The mean reciprocal rank and the Hits@k.
    """
    y_pred_pos = _host(y_pred_pos).reshape(-1, 1)
    y_pred_neg = _host(y_pred_neg)
    optimistic_rank = (y_pred_neg > y_pred_pos).sum(axis=1)
    pessimistic_rank = (y_pred_neg >= y_pred_pos).sum(axis=1)
    ranking_list = 0.5 * (optimistic_rank + pessimistic_rank) + 1
    hits = (ranking_list <= k).astype(np.float32)
    mrr = 1.0 / ranking_list.astype(np.float32)
    return float(mrr.mean()), float(hits.mean())

from mlx_graphs.metrics import tgb_mrr_hits · mlx_graphs/metrics/tgb.py