Skip to content

average_precision_score

average_precision_score(labels: ArrayLike, scores: ArrayLike) -> float

Average precision of binary labels ranked by scores.

\[ \text{AP} = \sum_n (R_n - R_{n-1}) P_n \]

where \(P_n\) and \(R_n\) are the precision and recall at the \(n\)-th distinct score threshold, as in scikit-learn's average_precision_score.

Parameters:

Name Type Description Default
labels ArrayLike

Binary ground truth (1 for positives), shape [n]

required
scores ArrayLike

Scores of the samples (higher means more likely positive), shape [n]

required

Returns:

Type Description
float

The average precision, between 0 and 1.

Example:

from mlx_graphs.metrics import average_precision_score

average_precision_score(mx.array([1, 0, 1, 0]),
                        mx.array([0.9, 0.1, 0.4, 0.5]))
>>> 0.8333
Source code in mlx_graphs/metrics/functional.py
def average_precision_score(labels: ArrayLike, scores: ArrayLike) -> float:
    r"""Average precision of binary ``labels`` ranked by ``scores``.

    .. math::
        \text{AP} = \sum_n (R_n - R_{n-1}) P_n

    where :math:`P_n` and :math:`R_n` are the precision and recall at the
    :math:`n`-th distinct score threshold, as in scikit-learn's
    ``average_precision_score``.

    Args:
        labels: Binary ground truth (``1`` for positives), shape `[n]`
        scores: Scores of the samples (higher means more likely positive),
            shape `[n]`

    Returns:
        The average precision, between 0 and 1.

    Example:

    .. code-block:: python

        from mlx_graphs.metrics import average_precision_score

        average_precision_score(mx.array([1, 0, 1, 0]),
                                mx.array([0.9, 0.1, 0.4, 0.5]))
        >>> 0.8333
    """
    labels = _host(labels, np.float64)
    scores = _host(scores, np.float64)
    num_pos = labels.sum()
    if num_pos == 0:
        raise ValueError("average_precision_score needs positive samples")

    order = np.argsort(-scores, kind="mergesort")
    scores, labels = scores[order], labels[order]
    # last position of each distinct threshold
    distinct = np.where(np.diff(scores))[0]
    threshold_idx = np.r_[distinct, labels.size - 1]
    tps = np.cumsum(labels)[threshold_idx]
    precision = tps / (threshold_idx + 1)
    recall = tps / num_pos
    recall_prev = np.r_[0.0, recall[:-1]]
    return float(np.sum((recall - recall_prev) * precision))

from mlx_graphs.metrics import average_precision_score · mlx_graphs/metrics/functional.py