Compute ROC AUC by counting ranked pairs

ROC AUC has a clean meaning: pick a random positive and a random negative; AUC is the chance the positive gets the higher score. Ties count as half.

Write roc_auc(y_true, scores) for binary labels. Return the AUC as a float. If there are no positives or no negatives, return 0.5.

Signaturedef roc_auc(y_true, scores)

Understand the idea

ROC AUC has a simple meaning: pick one random positive and one random negative; AUC is the probability the positive gets the higher score. So you can compute it by checking every positive and negative pair. A tie is a coin flip and counts as half. Like a tournament where every positive plays every negative and you count wins. Worked example: labels [1, 0, 1, 0], scores [0.8, 0.4, 0.4, 0.2]. Positives have scores 0.8 and 0.4; negatives have 0.4 and 0.2. Pairs: 0.8 vs 0.4 win, 0.8 vs 0.2 win, 0.4 vs 0.4 tie (0.5), 0.4 vs 0.2 win. Total 3.5 out of 4 pairs, so AUC = 0.875. AUC of 0.5 is random guessing and 1.0 is perfect ranking. If there are no positives or no negatives, return 0.5. Rule: AUC = (wins + 0.5 x ties) / (n_pos x n_neg). It is the usual metric for ranking-style classifiers like fraud or click models.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: perfect rankingroc_auc([0, 0, 1, 1], [0.1, 0.2, 0.8, 0.9])
  • Sample 2: with tiesroc_auc([0, 1, 0, 1], [0.5, 0.5, 0.2, 0.9])
  • Test 3: random-ishroc_auc([1, 0, 1, 0, 1, 0], [0.3, 0.6, 0.7, 0.2, 0.4, 0.4])
  • Test 4: one class onlyroc_auc([1, 1], [0.2, 0.3])