160. 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.
def roc_auc(y_true, scores)ROC curve and AUC
Each threshold gives one point (false positive rate, true positive rate). Better separated classes push the curve to the top left.
| predicted 1 | predicted 0 | |
|---|---|---|
| actual 1 | TP 114 | FN 36 |
| actual 0 | FP 33 | TN 117 |
- precision
- 0.776
- recall
- 0.76
- F1
- 0.768
- MCC
- 0.54
- ROC AUC
- 0.849
Synthetic scores made in your browser: 150 per class, sigmoid of a normal value centred at ±separation / 2. AUC counts every positive and negative pair.
Example 1
Input: y_true = [0, 0, 1, 1], scores = [0.1, 0.2, 0.8, 0.9]
Output: 1.0
Example 2
Input: y_true = [0, 1, 0, 1], scores = [0.5, 0.5, 0.2, 0.9]
Output: 0.875
Example 3
Input: y_true = [1, 0, 1, 0, 1, 0], scores = [0.3, 0.6, 0.7, 0.2, 0.4, 0.4]
Output: 0.611111
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Loop over every (positive, negative) pair: add 1 if the positive's score is higher, 0.5 if equal.
Hint 2
Divide by n_pos * n_neg.
Hint 3
Fine for small inputs.
Common mistakes
- Ignoring ties (the buggy version) underestimates AUC for models that output coarse 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.
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.
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.
Topics
Companies3
- ByteDance the topic appears in interview reports ByteDance Machine Learning Engineer Interview Process
- Google the topic appears in interview reports Google Machine Learning Engineer Interview Guide (Interview Query)
- Microsoft a candidate reported this question Microsoft Machine Learning Engineer Interview Questions | Screna AI
From public interview reports and guides. Not affiliated with or endorsed by these companies.