---
title: ROC-AUC from scores (with ties)
url: https://gurkanozkan.ai/learn/coding/mle-roc-auc-from-scores-with-ties-16/
markdown: https://gurkanozkan.ai/learn/coding/mle-roc-auc-from-scores-with-ties-16.md
kind: coding
difficulty: Medium
topics:
  - Metrics
  - Ranking
  - Sorting
json: https://gurkanozkan.ai/api/learn/coding/mle-roc-auc-from-scores-with-ties-16.json
robots: noindex
---

# ROC-AUC from scores (with ties)

Return the probability that a randomly chosen positive gets a higher score than a randomly chosen negative, counting ties as 0.5. Raise `ValueError` if either class is absent. Aim for O(n log n).

## Signature

```python
def roc_auc(y_true: list[int], scores: list[float]) -> float: ...
```

## Examples

Each call and the value it should give.

```python
>>> close(roc_auc([0, 0, 1, 1], [0.1, 0.2, 0.8, 0.9]), 1.0)
True

>>> close(roc_auc([0, 0, 1, 1], [0.9, 0.8, 0.2, 0.1]), 0.0)
True
```

## Hints

1. Sort by score descending; sum over positives the number of negatives below them.
2. Equivalently, count (positive, negative) pairs with positive score higher.
3. Ties contribute 0.5 — handle tied scores explicitly.

## Reference solution

```python
def roc_auc(y_true, scores):
    pos = [s for y, s in zip(y_true, scores) if y == 1]
    neg = [s for y, s in zip(y_true, scores) if y == 0]
    if not pos or not neg:
        raise ValueError("need both classes")
    # rank-based O(n log n)
    pairs = sorted(zip(scores, y_true))
    ranks = [0.0] * len(pairs)
    i = 0
    while i < len(pairs):
        j = i
        while j + 1 < len(pairs) and pairs[j + 1][0] == pairs[i][0]:
            j += 1
        avg = (i + j) / 2 + 1
        for t in range(i, j + 1):
            ranks[t] = avg
        i = j + 1
    rpos = sum(r for r, (_, y) in zip(ranks, pairs) if y == 1)
    P, N = len(pos), len(neg)
    return (rpos - P * (P + 1) / 2) / (P * N)
```

## What a strong solution covers

- Rank-sum (Mann–Whitney) formulation with average ranks for ties, or a sorted sweep.
- Handles the degenerate single-class case.
- Explains the link to the ROC curve's trapezoidal area.

## Common mistakes

- the O(P·N) pairwise loop at scale
- ignoring ties (biased AUC).
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
