Take 1,000 rows, half of them positive, and a model that says 0.5 for every row. It knows nothing, so its AUC should be 0.5. If you write the usual loop (sort by score, walk down, add up the area) you'll get 1.0 when the positives happen to come first in your file and 0.0 when the negatives do. I've run both.

import numpy as np def auc_with_a_bug(y, score): y = np.asarray(y)[np.argsort(-np.asarray(score), kind="stable")] P, N = y.sum(), len(y) - y.sum() tp = fp = area = px = py = 0 for v in y: if v: tp += 1 else: fp += 1 x, t = fp / N, tp / P area += (x - px) * (t + py) / 2 px, py = x, t return area 

When the scores are tied the sort leaves them in whatever order they came in, and the loop goes through them one at a time as if that order meant something.

It happens to sensible models too

You might think nobody's model says 0.5 for everything, and that's fair. But people round their scores, and trees give you the same score for everything in a leaf, so I tried it on something more normal. I made 500 positives and 500 negatives with scores that overlap a good deal (the real AUC is 0.698) and then rounded the probabilities.

Scores kept to Different scores Correct AUC Loop, positives first Loop, negatives first
full precision 1000 0.698 0.698 0.698
2 decimals 91 0.699 0.704 0.693
1 decimal 10 0.691 0.750 0.633
0 decimals 2 0.658 0.884 0.432

At one decimal place the same predictions are 0.750 or 0.633 depending on how your file was sorted, and you could easily ship a model because of a difference half that size. Files do get sorted by label more often than you'd think (somebody's concatenated the positives and the negatives).

The fix

AUC is the chance that a random positive scores above a random negative, and a tie counts as a half. So you can just count it, which is fine when you haven't got too many rows.

def auc(y, score): y, s = np.asarray(y), np.asarray(score) p, n = s[y == 1][:, None], s[y == 0][None, :] return ((p > n).sum() + 0.5 * (p == n).sum()) / (p.size * n.size) 

For a big set I'd use average ranks, which gives you the same number after one sort. If you'd rather keep the loop, only add a point to the curve when the score changes, so all the tied rows go in together and you get a straight diagonal line across them.

I'd test any AUC you've written with a constant score, because it takes one line and the answer has to be 0.5. The rank version and the rest of what you'd be asked about it in an interview are at https://academicquant.co.uk/ml-roc-auc?utm_source=devto&utm_medium=post&utm_campaign=devto-auc-ties