AUC: Checking Every Positive-Negative Pair

Metrics & EvaluationMedium+15 XP+15

AUC: Checking Every Positive-Negative Pair

Accuracy makes you pick a threshold first. AUC doesn't — it scores how well your model orders the data, which is a property of the scores alone.

It has a reading you can say out loud: AUC is the chance that a randomly chosen positive example scores higher than a randomly chosen negative one. And because it's a chance over pairs, you can compute it by just checking every pair.

Task: write auc(y_true, scores) returning that value, rounded to 4 decimal places.

Take every possible pairing of one positive example with one negative example. For each pair, award:

  • 1 if the positive scored higher,
  • 0.5 if the two scored exactly the same,
  • 0 if the positive scored lower.

AUC is the average award across all those pairs — the total divided by number of positives × number of negatives.

  • y_true holds 1 for positive and 0 for negative, and always contains at least one of each.
  • scores can be any numbers, not just probabilities. Only their ordering matters.
  • The half-point for a tie is what keeps the metric honest: a model that gives everything the same score has learned no ordering at all, and should land at 0.5.

And a model that gets the ordering exactly backwards scores 0.0 — worse than useless, but trivially fixable by flipping the sign.

Examples

y_true = [1, 0, 1, 0]
scores = [0.9, 0.4, 0.6, 0.2]
returns 1.0
y_true = [1, 0, 1, 0]
scores = [0.5, 0.5, 0.5, 0.5]
returns 0.5

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run