Sub topic 8
AUC as the probability of ranking a positive above a negative
This chapter assumes you can build a ROC curve by sweeping a threshold, that you know TPR and FPR, and that you are comfortable with NumPy. Earlier chapters defined AUC as the area under the ROC curve. Here you will see that the same number has a second meaning, and that the second meaning explains most of AUC's strengths and blind spots.
The claim
Pick one positive example and one negative example at random from your test set. Look at the scores your model gave them. The AUC is the probability that the positive example has the higher score. If the two scores are equal, count that pair as one half.
Written as a formula, with positive scores $s^+i$ for $i = 1..n+$ and negative scores $s^-j$ for $j = 1..n-$:
AUC = (1 / (n₊ · n₋)) × Σᵢ Σⱼ [ 1 if s⁺ᵢ > s⁻ⱼ, 0.5 if s⁺ᵢ = s⁻ⱼ, 0 otherwise ]
This is an exact identity for the empirical ROC curve, not an approximation. The area under the staircase of ROC points equals this pair-counting average.
Why the two definitions agree
Moving along the ROC curve means lowering the threshold. Each time the threshold passes a positive example, the curve steps up by 1/n₊. Each time it passes a negative example, the curve steps right by 1/n₋.
Consider one positive example. The area under the curve to the right of its upward step is a strip of width equal to the fraction of negatives that have not yet been passed. Those negatives are exactly the ones with a lower score than this positive. So each positive contributes (1/n₊) × (fraction of negatives it outranks). Averaging over positives gives the pair-counting formula.
When a positive and a negative share a score, the threshold passes both at once. The curve moves diagonally, and the triangle under that diagonal contributes half a unit of area. That is where the 0.5 for ties comes from.
A worked example
Use the four examples from the earlier chapters. The positives have scores 0.35 and 0.8. The negatives have scores 0.1 and 0.4.
| Positive score | Negative score | Positive ranked higher? | Pair value |
|---|---|---|---|
| 0.35 | 0.1 | yes | 1 |
| 0.35 | 0.4 | no | 0 |
| 0.8 | 0.1 | yes | 1 |
| 0.8 | 0.4 | yes | 1 |
Three of four pairs are correctly ordered, so AUC = 3/4 = 0.75. This matches the area from roc_auc_score. The single mistake is the pair (0.35, 0.4): a negative example scored above a positive one.
Computing it three ways
The code below computes AUC from the ROC curve, from explicit pairs, and from ranks. It uses a second dataset with a tie, so you can see that all three methods handle ties the same way.
import numpy as np
from scipy.stats import rankdata
from sklearn.metrics import roc_auc_score
def auc_pairs(y_true, y_score):
y_true = np.asarray(y_true)
y_score = np.asarray(y_score)
pos = y_score[y_true == 1]
neg = y_score[y_true == 0]
diff = pos[:, None] - neg[None, :]
return ((diff > 0).sum() + 0.5 * (diff == 0).sum()) / diff.size
def auc_ranks(y_true, y_score):
y_true = np.asarray(y_true)
y_score = np.asarray(y_score)
n_pos = (y_true == 1).sum()
n_neg = (y_true == 0).sum()
ranks = rankdata(y_score) # tied scores get the average rank
rank_sum = ranks[y_true == 1].sum()
return (rank_sum - n_pos * (n_pos + 1) / 2) / (n_pos * n_neg)
datasets = {
"no ties": (np.array([0, 0, 1, 1]), np.array([0.1, 0.4, 0.35, 0.8])),
"one tie": (np.array([0, 1, 0, 1]), np.array([0.5, 0.5, 0.2, 0.9])),
}
for name, (y_true, y_score) in datasets.items():
print(
name,
roc_auc_score(y_true, y_score),
auc_pairs(y_true, y_score),
auc_ranks(y_true, y_score),
)
# no ties 0.75 0.75 0.75
# one tie 0.875 0.875 0.875In the tie dataset, the positive with score 0.5 and the negative with score 0.5 form a tied pair worth 0.5. The other three pairs are all correct, so the total is 3.5 / 4 = 0.875.
The rank version is the practical one. auc_pairs builds an n_pos × n_neg matrix, which uses too much memory for large test sets. The rank method sorts once and runs in O(n log n) time. It is the Mann-Whitney U statistic divided by n_pos * n_neg. If you have seen the Wilcoxon rank-sum test, that is the same quantity. The rank-sum test asks whether one group's scores tend to be higher than the other's, and AUC reports how large that tendency is.
What the ranking view tells you
AUC only depends on order
The pair comparison uses only "greater than", "equal", and "less than". Any strictly increasing transformation of the scores leaves every comparison unchanged, so AUC is unchanged too. Taking a logarithm, squaring positive scores, or passing log-odds through a sigmoid does not change AUC.
import numpy as np
from sklearn.metrics import roc_auc_score
y_true = np.array([0, 0, 1, 1])
y_score = np.array([0.1, 0.4, 0.35, 0.8])
print(roc_auc_score(y_true, y_score)) # 0.75
print(roc_auc_score(y_true, np.log(y_score))) # 0.75
print(roc_auc_score(y_true, y_score ** 3)) # 0.75
print(roc_auc_score(y_true, -y_score)) # 0.25The last line shows the other side of this property. Negating the scores reverses every comparison, so AUC becomes 1 - 0.75 = 0.25. An AUC well below 0.5 usually means the score direction is flipped, for example a model that outputs the probability of the wrong class. It does not mean the model has no information.
AUC ignores calibration
Because only order matters, a model whose probabilities are badly miscalibrated can have the same AUC as a perfectly calibrated one. A model that says 0.51 for every positive and 0.49 for every negative has AUC = 1.0. If you need to trust the probability values themselves, for example to compute expected cost, check calibration separately.
AUC is threshold-free, and also context-free
The pairwise definition never mentions a threshold. That makes AUC useful for comparing models before you decide where to operate. It also means AUC averages over all operating regions, including ones you will never use. Two models with the same AUC can behave very differently in the low-FPR region you care about.
0.5 is the baseline
If scores carry no information about the label, a random positive outranks a random negative half the time. So the diagonal ROC line has AUC = 0.5. This reading makes the number concrete: AUC = 0.9 means that in 90% of positive-negative pairs, the model orders them correctly.
Edge cases
Ties
Ties happen often with models that output few distinct values, such as shallow decision trees, or with rounded scores. Counting ties as 0.5 is the convention scikit-learn follows. The consequence is that coarse scores are penalized only mildly: a model that outputs a single constant for every example gets AUC = 0.5, since every pair is tied.
If you convert a score to hard 0/1 predictions and then compute AUC, you get a single ROC point joined to the corners by straight lines. The result is (TPR + TNR) / 2, which is balanced accuracy. This is a common mistake: passing predict() output where predict_proba() or decision_function() output was meant.
Unequal group sizes
The formula divides by n_pos * n_neg, so each pair has equal weight. A positive is compared with every negative, no matter how many of either exist. This is why AUC does not change when you add more negatives drawn from the same distribution. The expected value stays the same, though the estimate becomes less noisy. Section "Class imbalance and precision-recall curves" later in this tutorial returns to why this stability can hide poor performance on rare positives.
Only one class present
If the test set has no positives or no negatives, there are no pairs and AUC is undefined. roc_auc_score raises a ValueError in that case. This often happens in small cross-validation folds with rare classes, so use stratified splits.
Common errors
- Passing hard labels instead of scores, which collapses the curve to one point.
- Reading AUC < 0.5 as "worse than random" and discarding the model, when the sign of the score is reversed.
- Using the pairwise matrix on large datasets and running out of memory. Use ranks instead.
- Treating a high AUC as evidence that probabilities are calibrated.
- Reporting a single AUC value without any sense of its variability. A later chapter shows how to bootstrap it.
Exercise
A test set has three positives with scores 0.9, 0.6, 0.6 and two negatives with scores 0.6, 0.3. Compute the AUC by listing the six positive-negative pairs. Then say what AUC you would get if every score were replaced by its square.
Show answer
Pairs for the positive 0.9: against 0.6 it wins (1), against 0.3 it wins (1), total 2. Each positive 0.6: against negative 0.6 it ties (0.5), against negative 0.3 it wins (1), total 1.5 each, so 3 for both. The sum is 2 + 3 = 5 over 6 pairs, so AUC = 5/6 ≈ 0.833. Squaring positive scores is a strictly increasing transformation, so every comparison and every tie is unchanged, and AUC stays 5/6 ≈ 0.833.
Exercise
A colleague trains a classifier and reports AUC = 0.12 on a held-out set. Name the most likely cause and the one-line fix, and state the AUC you expect after the fix.
Show answer
The scores are probably oriented the wrong way, for example the model's score for the negative class was passed as the positive-class score. Pass the score for the positive class, or negate the scores. Reversing every comparison gives AUC = 1 - 0.12 = 0.88.