ROC-AUC from scores (with ties)
Problem
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
def roc_auc(y_true: list[int], scores: list[float]) -> float: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> 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)
TrueHints
Sort by score descending; sum over positives the number of negatives below them.
Equivalently, count (positive, negative) pairs with positive score higher.
Ties contribute 0.5 — handle tied scores explicitly.
Reference solution
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).