Lesson 7.3: Four ways to calculate the AUC by hand
Calculate the AUC four ways: count pairs, sum ranks, apply the trapezoid rule to the ROC curve and convert the Gini, on a toy portfolio and then on real data.
By the end of this lesson you will be able to calculate the area under the ROC curve in four different ways: by comparing every bad loan with every good loan, by summing ranks, by the trapezoid rule applied to the ROC curve and from the Gini coefficient of the CAP curve. You will do each by hand on a toy portfolio of seven loans, see that all four give the same answer, check them against the 3,000-loan holdout sample, handle tied scores correctly, compute the AUC from a table of score bands when only grouped data are available and choose the method that suits the job. You should have read Lessons 7.1 and 7.2, which defined the curves, the Gini coefficient and the AUC. The arithmetic is counting and adding, and it is worth doing at least once with a pencil, because the practice turns a number from a software package into something you understand.
Lesson 7.2 gave the AUC as the area under a curve. That definition is correct and awkward: it suggests that the calculation needs integration, and it hides what the number means. In fact, the AUC has several equivalent definitions, and each is useful in a different setting. Knowing them lets you check software, compute the number when you have only summary tables and explain it to a colleague who has never seen a ROC curve.
What the AUC really measures
Before the methods, here is the meaning that connects them all.
> AUC = the probability that a randomly chosen bad loan has a worse score than a randomly chosen good loan. If the two have the same score, count it as half.
That is all. An AUC of 0.694 means that if you pick one bad borrower and one good borrower at random from the holdout, there is a 69.4 per cent chance that the scorecard ranks the bad one as riskier. A value of 0.5 is a coin toss. A value of 1 means that every bad borrower is ranked as riskier than every good one. Each of the four methods below is a different route to the same probability.
A toy portfolio
To keep the arithmetic visible, use a small portfolio: 3 bad loans and 4 good loans, with these scores (a higher score means safer).
Loan · Outcome · ScoreA · Bad · 520
B · Good · 530
C · Bad · 540
D · Good · 560
E · Bad · 580
F · Good · 590
G · Good · 600
There are 3 × 4 = 12 pairs of one bad loan and one good loan. Each method must give the same AUC for this portfolio. The answer will turn out to be 0.75.
Method 1: count the pairs
This follows the meaning directly. For each of the 12 pairs, ask whether the bad loan has the lower score (which is the correct ranking) and count it.
Bad loan A (520): lower than every good loan, 530, 560, 590 and 600. That is 4 correct pairs.
Bad loan C (540): lower than 560, 590 and 600, but not lower than 530. That is 3 correct pairs.
Bad loan E (580): lower than 590 and 600, but not lower than 530 or 560. That is 2 correct pairs.
Total correct pairs: 4 + 3 + 2 = 9 out of 12. There are no ties. The AUC is 9 ÷ 12 = 0.75.
When the scores of a bad and a good loan are equal, the pair is a tie and counts as one half. The general formula is:
> AUC = (concordant pairs + 0.5 × tied pairs) ÷ (number of bad loans × number of good loans)
This method is perfect for understanding and for tiny datasets, and hopeless for large ones: the holdout sample of this module has 313 × 2,687 = 841,031 pairs, which a computer handles, but a data set of a million loans has billions.
Method 2: sum the ranks
A shortcut avoids comparing every pair. Rank all the loans together by score from the safest (rank 1) to the riskiest (rank 7). Then add up the ranks of the bad loans.
Loan · Score · Rank, safest = 1 · OutcomeG · 600 · 1 · Good
F · 590 · 2 · Good
E · 580 · 3 · Bad
D · 560 · 4 · Good
C · 540 · 5 · Bad
B · 530 · 6 · Good
A · 520 · 7 · Bad
The ranks of the bad loans are 3, 5 and 7, which add to 15. Now subtract the smallest possible total, which is what the sum would be if the three bad loans held the three lowest ranks, 1 + 2 + 3 = 6. In general that is nbad × (nbad + 1) ÷ 2 = 3 × 4 ÷ 2 = 6. The difference is called U:
> U = sum of ranks of bad loans − nbad × (nbad + 1) ÷ 2 = 15 − 6 = 9
And the AUC is U ÷ (nbad × ngood) = 9 ÷ 12 = 0.75, the same as before. The number U is exactly the number of correct pairs from Method 1. This is the Mann-Whitney U statistic, from statistics, and the method is the standard way software computes the AUC, because sorting a list of n loans takes far less work than comparing n² pairs.
Predict first: if two loans had the same score, what would their ranks be, and what would that do to the sum? Think about it before reading on.
Tied loans each get the average of the ranks they would have held. Two tied loans occupying ranks 4 and 5 would each be given rank 4.5. The rank sum then counts a bad-good tie as exactly half a correct pair, which is just the convention of Method 1. This is why rank-based software handles ties correctly with no extra work.
Method 3: the trapezoid rule on the ROC curve
The third method follows the definition of Lesson 7.2: build the ROC curve and measure the area under it. Move the cut-off from the riskiest score upwards. At each step, reject every loan with a score at or below the cut-off, and record the share of bad loans rejected (the true positive rate) and the share of good loans rejected (the false positive rate).
Reject scores up to · Bad rejected · Good rejected · True positive rate · False positive rate(nothing) · 0 · 0 · 0 · 0
520 · 1 · 0 · 1/3 · 0
530 · 1 · 1 · 1/3 · 1/4
540 · 2 · 1 · 2/3 · 1/4
560 · 2 · 2 · 2/3 · 2/4
580 · 3 · 2 · 1 · 2/4
590 · 3 · 3 · 1 · 3/4
600 · 3 · 4 · 1 · 1
Now add up the area as a sum of strips. Each time the false positive rate moves right by an amount, the area under the curve grows by that width times the average height of the strip. Going through the table:
From 0 to 1/4 on the horizontal axis (the step from 520 to 530), the height is 1/3: area = 1/4 × 1/3 = 0.0833.
From 1/4 to 2/4 (the step from 540 to 560), the height is 2/3: area = 1/4 × 2/3 = 0.1667.
From 2/4 to 3/4 (the step from 580 to 590), the height is 1: area = 1/4 × 1 = 0.25.
From 3/4 to 1 (the step from 590 to 600), the height is 1: area = 1/4 × 1 = 0.25.
The steps in which only the true positive rate moves (straight up) add no area. Total: 0.0833 + 0.1667 + 0.25 + 0.25 = 0.75. The same answer again.
When many loans share a score, the curve has diagonal segments instead of steps, and the strip is a trapezoid: its area is the width times the average of the two heights. That is why the method is called the trapezoid rule, and it is exactly the half-credit for ties of the other methods.
Method 4: from the Gini of the CAP curve
The fourth method uses Lesson 7.2's CAP curve. Sort the loans from the riskiest to the safest and record, at each point, the share of all loans passed (x) and the share of all bad loans caught (y).
Loans passed · Share of loans, x · Bad loans caught · Share of bads, y0 · 0 · 0 · 0
1 (A) · 1/7 · 1 · 1/3
2 (B) · 2/7 · 1 · 1/3
3 (C) · 3/7 · 2 · 2/3
4 (D) · 4/7 · 2 · 2/3
5 (E) · 5/7 · 3 · 1
6 (F) · 6/7 · 3 · 1
7 (G) · 1 · 3 · 1
Each step has a width of 1/7. Using the trapezoid rule, the area under the curve is 1/7 × [ (0 + 1/3)/2 + (1/3 + 1/3)/2 + (1/3 + 2/3)/2 + (2/3 + 2/3)/2 + (2/3 + 1)/2 + (1 + 1)/2 + (1 + 1)/2 ] = 1/7 × [0.1667 + 0.3333 + 0.5 + 0.6667 + 0.8333 + 1 + 1] = 4.5 ÷ 7 = 0.6429.
The area under the perfect CAP curve is 1 − p ÷ 2, where p is the bad rate, here 3 ÷ 7 = 0.4286. So the perfect area is 1 − 0.2143 = 0.7857. Then:
> Gini = (0.6429 − 0.5) ÷ (0.7857 − 0.5) = 0.1429 ÷ 0.2857 = 0.50
And AUC = (Gini + 1) ÷ 2 = (0.50 + 1) ÷ 2 = 0.75. All four methods agree.
Method · Calculation · Result1. Count pairs · 9 correct pairs out of 12 · 0.75
2. Sum ranks · (15 − 6) ÷ 12 · 0.75
3. Trapezoid under the ROC · 0.0833 + 0.1667 + 0.25 + 0.25 · 0.75
4. From Gini of the CAP · (0.50 + 1) ÷ 2 · 0.75
## The same four on the real data
Apply them to the holdout sample of 3,000 loans, with 313 bad and 2,687 good, scored by the scorecard.
Method 1, pairs. There are 313 × 2,687 = 841,031 pairs. A computer counts that 578,567 have the bad loan with the lower score (concordant), 10,125 have equal scores (ties) and the remaining 841,031 − 578,567 − 10,125 = 252,339 have the bad loan with the higher score (discordant). The AUC is (578,567 + 0.5 × 10,125) ÷ 841,031 = 583,629.5 ÷ 841,031 = 0.6939.
Method 2, ranks. Rank all 3,000 loans from the safest to the riskiest, giving tied loans the average rank. The ranks of the 313 bad loans add to 632,770.5. The smallest possible total is 313 × 314 ÷ 2 = 49,141. So U = 632,770.5 − 49,141 = 583,629.5, exactly the same as the count in Method 1 (578,567 + 5,062.5). Then AUC = 583,629.5 ÷ 841,031 = 0.6939.
Method 3, trapezoid. The ROC curve of the holdout has 97 points, one for each distinct score. The trapezoid rule over those points gives 0.6939.
Method 4, Gini. The area under the CAP curve is 0.6737 and the perfect area is 0.9478, giving a Gini of 0.3879. The AUC is (0.3879 + 1) ÷ 2 = 0.6939.
All four are the same to four decimal places, as they must be.
When only grouped data are available
Often you have a table of score bands, not the loan-level data: how many good and bad loans fell in each band. The AUC can still be computed. Use Method 3 on the bands: build ROC points from the cumulative percentages of bads and goods at the end of each band, then apply the trapezoid rule. For the twelve ten-point bands of Lesson 7.1, the points are (false positive rate, true positive rate) of (1.3, 10.2), (3.1, 16.3), (7.6, 27.5), (15.0, 40.6), (26.0, 54.0), (39.4, 67.1), (54.4, 78.3), (68.7, 87.2), (82.0, 93.3), (89.4, 98.1), (96.5, 98.7) and (100, 100). The trapezoid area is 0.6941, against 0.6939 from the loan-level data.
The difference is 0.0002. The grouped calculation treats all loans within a band as tied, which gives half credit for every bad-good pair within a band. The detail inside bands carries almost no information in this case, so little is lost. With only a handful of coarse bands (say four), the loss can be larger, and a grouped AUC is a slight under- or over-estimate depending on the ordering inside bands. For reporting, ten or more bands are usually enough.
Which method to use
Method · Best for · Watch out forCount pairs · Understanding, tiny samples, checking · Cost grows with the product of the group sizes
Sum ranks · Software, large samples, with ties handled by average ranks · Be sure about the direction of ranking
Trapezoid on the ROC · Drawing the curve, grouped data · Needs the curve points, ties give diagonal segments
Gini from the CAP · Supervisory reporting that uses Gini · Needs the bad rate for the perfect curve
In practice, analysts compute the AUC with a library function that uses the rank method, and use the others as checks and to explain the figure. A good validation habit is to compute the number two ways and confirm that they agree: a mismatch usually means that the direction of the score is reversed, or that ties were handled differently, or that the sample differs.
A common trap: the direction of the score
A frequent mistake is to feed software a score where a higher value means safer, when the function expects a higher value to mean more likely to be bad. The AUC then comes out as one minus the true value. If you see an AUC of 0.31 for a model you expected to be decent, flip the score and recompute: 1 − 0.31 = 0.69. An AUC well below 0.5 is a model that works backwards, which is usually a sign of a sign error, not of a model that is skilfully wrong. In the toy example, if you reversed the score you would count 3 correct pairs instead of 9, and the AUC would be 3 ÷ 12 = 0.25, which is 1 − 0.75.
The four methods in Python
Each method is a few lines. The code below reproduces the toy example and the holdout calculation.
python
import numpy as np
import pandas as pd
from scipy.stats import rankdata
toy example
scores = np.array([520, 530, 540, 560, 580, 590, 600])
bad = np.array([1, 0, 1, 0, 1, 0, 0])
def aucpairs(scores, bad):
b, g = scores[bad == 1], scores[bad == 0]
conc = sum((bi < gj) for bi in b for gj in g)
tie = sum((bi == gj) for bi in b for gj in g)
return (conc + 0.5 tie) / (len(b) len(g))
def aucranks(scores, bad):
ranks = rankdata(-scores) # safest = rank 1, ties get average ranks
nb, ng = bad.sum(), (1 - bad).sum()
u = ranks[bad == 1].sum() - nb (nb + 1) / 2
return u / (nb ng)
def aucroc(scores, bad):
order = np.argsort(scores, kind="stable") # riskiest first
b, g = bad[order], 1 - bad[order]
tpr = np.r[0, np.cumsum(b) / b.sum()]
fpr = np.r[0, np.cumsum(g) / g.sum()]
return np.trapz(tpr, fpr)
def aucgini(scores, bad):
order = np.argsort(scores, kind="stable")
n, p = len(bad), bad.mean()
x = np.r[0, np.arange(1, n + 1) / n]
y = np.r[0, np.cumsum(bad[order]) / bad.sum()]
gini = (np.trapz(y, x) - 0.5) / ((1 - p / 2) - 0.5)
return (gini + 1) / 2
for f in (aucpairs, aucranks, aucroc, aucgini):
print(f.name, round(f(scores, bad), 4))
On the toy data the four functions print 0.75 each. On loan-level data with ties, the ROC and CAP versions should group tied scores before accumulating, or they will differ slightly from the pair and rank versions. A library routine does this for you, and it is wise to check against one.
A worked example: reconciling two reports
A model validation team receives two reports on the same scorecard and the same holdout sample. One, from the development team, says "AUC 0.694". The other, from a vendor tool, says "AUC 0.306".
1. Spot the pattern. 0.694 + 0.306 = 1.000. The two numbers are complements, so the likelihood is that the two tools used opposite conventions for the direction of the score.
2. Check the direction. The vendor's tool took a higher score to mean a higher probability of default, but the score of this scorecard is higher for safer borrowers. So it reversed the ranking.
3. Check with the Gini. The development team's Gini is 2 × 0.694 − 1 = 0.388. The vendor's Gini would be 2 × 0.306 − 1 = −0.388. The signs are opposite and the magnitudes are the same.
4. Fix and document. The vendor is asked to supply the probability of default (or the negative of the score) as input. Rerun gives 0.694.
5. Record the convention. The validation report states, for every metric, whether a higher score means safer or riskier.
A five-minute check removed what could have been a long argument about whether the model was good or bad.
Common mistakes
Reversing the score. An AUC below 0.5 usually means the direction is wrong, so flip it before drawing conclusions.
Ignoring ties. Tied scores should get half credit, or average ranks.
Using the wrong subtraction in the rank method. Subtract nbad × (nbad + 1) ÷ 2, and check the direction of ranking.
Comparing AUCs computed on grouped and loan-level data without comment. They differ slightly.
Computing on the development sample. Use a holdout.
Forgetting that AUC is a probability about pairs. It is not the share of loans classified correctly.
Trusting software without a cross-check. Compute a second way on a small subset.
Not stating the convention. Say what a higher score means in every report.
Key takeaways
The AUC is the probability that a randomly chosen bad loan is ranked riskier than a randomly chosen good loan, with ties counting half.
Four methods give the same number: count the pairs, sum the ranks, apply the trapezoid rule to the ROC curve and convert the Gini of the CAP curve.
On the toy portfolio of 3 bad and 4 good loans, all four gave 0.75. The pair count was 9 of 12 and the rank sum was 15, giving U = 9.
On the holdout, 578,567 of 841,031 pairs were concordant and 10,125 were tied, giving an AUC of 0.6939 by every method.
Grouped data work too: the twelve score bands gave 0.6941, within 0.0002 of the loan-level figure.
Check the direction of the score. A reversed score turns an AUC of 0.694 into 0.306.
Check yourself
1. A portfolio has 2 bad and 5 good loans, and 7 of the 10 bad-good pairs are ranked correctly with no ties. What is the AUC?
7 ÷ 10 = 0.70.
2. In the rank method, the 4 bad loans have ranks that add to 30, with rank 1 for the safest loan. There are 12 good loans. What is the AUC?
U = 30 − 4 × 5 ÷ 2 = 20. AUC = 20 ÷ (4 × 12) = 0.4167. An AUC below 0.5 suggests the ranks may be reversed.
3. What rank does each of two tied loans get if they would have held ranks 6 and 7?
The average, 6.5 each.
4. A tool reports an AUC of 0.38 for a scorecard that should be reasonable. What is the first thing to check?
Whether the score direction is reversed. If so, the true AUC is 1 − 0.38 = 0.62.
5. Why does the grouped-band AUC differ slightly from the loan-level one?
Within a band, all loans are treated as tied and earn half credit, ignoring any ordering inside the band. With enough bands, the difference is tiny.
Try this
Compute the AUC four ways. Set aside forty to fifty minutes.
1. Invent a toy portfolio of 4 bad and 6 good loans with scores. Make the scores overlap so that some bad loans score above some good ones, and include one tie.
2. Compute the AUC by counting pairs, giving half credit for the tie.
3. Compute it by ranks. Rank the loans from the safest to the riskiest, give the tied loans their average rank, and compute U and the AUC.
4. Build the ROC points from the cumulative shares and compute the area with the trapezoid rule.
5. Build the CAP curve points, compute its area and the Gini, and convert to AUC.
6. Write the four results in a table and confirm that they agree. If they do not, find the slip.
7. Use the simulator with the holdout counts and then with your toy counts, and write three sentences: what the AUC means as a probability, which method you would trust for a million loans and one check you would always run before reporting it.
A good result is a table of four calculations with the same number, a clear statement of what the number means and a note of the checks you would run. Lesson 7.4 turns from measuring a scorecard to using it: choosing the risk cut-off.
Tags: Credit Risk Analytics AUC ROC Curve Mann-Whitney Model Validation