SDE & MLE Prep

ROC-AUC from Scratch

Key idea: AUC = probability a random positive outranks a random negative = normalized Mann–Whitney U statistic computed from ranks (ties get average ranks). O(N log N).

import numpy as np

def roc_auc(y_true, scores):
    y_true, scores = np.asarray(y_true), np.asarray(scores, float)
    order = np.argsort(scores)
    ranks = np.empty(len(scores))
    s = scores[order]
    i = 0
    while i < len(s):                                  # average ranks for ties
        j = i
        while j + 1 < len(s) and s[j + 1] == s[i]:
            j += 1
        ranks[order[i:j + 1]] = (i + j) / 2 + 1
        i = j + 1
    n_pos = y_true.sum(); n_neg = len(y_true) - n_pos
    return (ranks[y_true == 1].sum() - n_pos * (n_pos + 1) / 2) / (n_pos * n_neg)

assert roc_auc([0, 0, 1, 1], [0.1, 0.4, 0.35, 0.8]) == 0.75
assert roc_auc([0, 1], [0.5, 0.5]) == 0.5
assert roc_auc([0, 0, 1], [0.1, 0.2, 0.9]) == 1.0
print("ok")