Skip to content

tgb_ndcg

tgb_ndcg(y_true: ArrayLike, y_pred: ArrayLike, k: int = 10) -> float

NDCG@k of the predicted scores of each node over the classes, averaged over the nodes, as TGB (sklearn.metrics.ndcg_score(y_true, y_pred, k=k)).

The gains are the true label weights and the discount of position i (from 0) is 1 / log2(i + 2) for the first k positions and 0 after. Tied predicted scores share the average gain of their group, and nodes whose true labels are all zero score 0.

Parameters:

Name Type Description Default
y_true ArrayLike

Non-negative true label weights, shape [num_nodes, num_classes]

required
y_pred ArrayLike

Predicted scores, shape [num_nodes, num_classes]

required
k int

Only the first k ranked classes count. Default: 10

10

Returns:

Type Description
float

The mean NDCG@k.

Source code in mlx_graphs/metrics/tgb.py
def tgb_ndcg(y_true: ArrayLike, y_pred: ArrayLike, k: int = 10) -> float:
    r"""NDCG@k of the predicted scores of each node over the classes, averaged
    over the nodes, as TGB (``sklearn.metrics.ndcg_score(y_true, y_pred,
    k=k)``).

    The gains are the true label weights and the discount of position ``i``
    (from 0) is ``1 / log2(i + 2)`` for the first ``k`` positions and 0
    after. Tied predicted scores share the average gain of their group, and
    nodes whose true labels are all zero score 0.

    Args:
        y_true: Non-negative true label weights, shape `[num_nodes, num_classes]`
        y_pred: Predicted scores, shape `[num_nodes, num_classes]`
        k: Only the first ``k`` ranked classes count. Default: ``10``

    Returns:
        The mean NDCG@k.
    """
    y_true = _host(y_true)
    y_pred = _host(y_pred)
    if y_true.shape != y_pred.shape:
        raise ValueError(
            f"y_true and y_pred must have the same shape (got {y_true.shape} "
            f"and {y_pred.shape})"
        )
    if y_true.ndim != 2 or y_true.shape[1] <= 1:
        raise ValueError(
            "Computing NDCG is only meaningful with a 2D array of more than one "
            f"class per node (got shape {y_true.shape})"
        )
    if y_true.size and y_true.min() < 0:
        raise ValueError("ndcg only supports non-negative y_true values")

    discount = 1 / (np.log(np.arange(y_true.shape[1]) + 2) / np.log(2))
    discount[k:] = 0

    discount_cumsum = np.cumsum(discount)
    gain = np.asarray(
        [
            _tie_averaged_dcg(y_t, y_s, discount_cumsum)
            for y_t, y_s in zip(y_true, y_pred)
        ]
    )
    ranking = np.argsort(y_true)[:, ::-1]
    ranked = y_true[np.arange(ranking.shape[0])[:, np.newaxis], ranking]
    normalizing_gain = discount.dot(ranked.T)

    all_irrelevant = normalizing_gain == 0
    gain[all_irrelevant] = 0
    gain[~all_irrelevant] /= normalizing_gain[~all_irrelevant]
    return float(np.average(gain))

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