← Gym/AUC from Scratch
00:00/ 28 min

🧭 Do not search for the first 15 minutes. When stuck: re-read the requirements → define I/O → choose the data structure → trace a small example by hand → write code.

Implement auc_score(y_true, scores) — ROC-AUC without sklearn.

Input

python
y_true = [1, 0, 1, 0]           # 0 or 1
scores = [0.9, 0.8, 0.7, 0.1]   # model scores (they need not be probabilities)

Both lists have the same length.

What AUC means

The probability that a randomly drawn positive scores higher than a randomly drawn negative.

Do not integrate the curve — use the rank-based formula.

text
AUC = ( Σ(ranks of the positives) − P(P+1)/2 ) / (P · N)

P = number of positives, N = number of negatives
Ranks start at 1 in ascending score order (the lowest score gets rank 1)

Handling ties — the heart of this problem

Items with equal scores share the average of their ranks. If ranks 3 and 4 are tied, for instance, both become rank 3.5. Skip this and your value drifts on any data containing ties.

Edges

  • Return 0.0 when there are no positives or no negatives — the score is undefined there. Empty input falls under this too.
  • Round the result to 6 decimal places (round(x, 6)).

Level 1 · Rank-based AUC

Implement auc_score(y_true, scores). numpy is fine, and so is plain Python.