Skip to content

roc_auc_score

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

Area under the ROC curve of binary labels ranked by scores.

Computed with the Mann-Whitney U statistic, tied scores getting their average rank, which gives the same value as scikit-learn's roc_auc_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 AUC, between 0 and 1.

Example:

from mlx_graphs.metrics import roc_auc_score

roc_auc_score(mx.array([1, 0, 1, 0]), mx.array([0.9, 0.1, 0.4, 0.5]))
>>> 0.75
Source code in mlx_graphs/metrics/functional.py
def roc_auc_score(labels: ArrayLike, scores: ArrayLike) -> float:
    """Area under the ROC curve of binary ``labels`` ranked by ``scores``.

    Computed with the Mann-Whitney U statistic, tied scores getting their
    average rank, which gives the same value as scikit-learn's
    ``roc_auc_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 AUC, between 0 and 1.

    Example:

    .. code-block:: python

        from mlx_graphs.metrics import roc_auc_score

        roc_auc_score(mx.array([1, 0, 1, 0]), mx.array([0.9, 0.1, 0.4, 0.5]))
        >>> 0.75
    """
    labels = _host(labels, bool)
    scores = _host(scores, np.float64)
    num_pos = int(labels.sum())
    num_neg = labels.size - num_pos
    if num_pos == 0 or num_neg == 0:
        raise ValueError("roc_auc_score needs both positive and negative samples")

    order = np.argsort(scores, kind="mergesort")
    sorted_scores = scores[order]
    ranks = np.empty(scores.size, dtype=np.float64)
    # average (1-based) rank of each group of tied scores
    _, start, counts = np.unique(sorted_scores, return_index=True, return_counts=True)
    avg_rank = start + (counts + 1) / 2.0
    ranks[order] = np.repeat(avg_rank, counts)
    sum_pos_ranks = ranks[labels].sum()
    return float((sum_pos_ranks - num_pos * (num_pos + 1) / 2.0) / (num_pos * num_neg))

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