Lesson 7.1: The confusion matrix and the KS statistic
Judge a scorecard with a confusion matrix and the KS statistic: sensitivity, specificity, precision, the accuracy trap and the cumulative good and bad curves.
By the end of this lesson you will be able to build a confusion matrix for a scorecard at any cut-off, calculate sensitivity, specificity, precision and accuracy from it, explain why accuracy is a misleading measure when bad loans are rare, build the table of cumulative percentages of good and bad loans by score band, read off the Kolmogorov-Smirnov, or KS, statistic and say where on the score scale it occurs, and judge whether a KS value is weak, acceptable or too good to be true. You should have read Modules 5 and 6, which built the scorecard whose performance is measured here. The arithmetic is counting, percentages and one maximum, and every figure comes from a calculation on the data described below.
Module 6 built models and showed AUC and KS values without defining them. Module 7 is about measurement: how do you know that a scorecard is any good? A model can look reasonable on its coefficients and still fail in use, and a lender needs numbers that say how well it separates the borrowers who will repay from those who will not, how well its probabilities match reality and where the cut-off should be. This lesson starts with the two most common tools for judging separation at a cut-off and over the whole score range.
The data used in this module
Lessons 7.1 to 7.5 use the holdout sample of the synthetic data of Lesson 6.1: 3,000 loans, of which 313 are bad and 2,687 are good, a bad rate of 10.4 per cent. Each loan has the score from the scorecard of Lesson 6.2, with scores running from 512 to 629 in whole points. A higher score means a safer borrower. The holdout played no part in building the model, so the measures here are honest about how it would perform on new applicants. The data are synthetic, built for this course, so the figures show how the measures behave and are not statistics about real borrowers.
Why accuracy is not enough
The obvious question about any prediction is: how often is it right? For a scorecard, though, the answer depends on a cut-off: a score below which you predict that the borrower will default. Everyone below the cut-off is rejected (or sent for review) and everyone above it is approved. Once you fix a cut-off, every loan falls into one of four cases.
· Actually bad · Actually goodRejected (score below the cut-off) · True positive (TP): a bad loan correctly rejected · False positive (FP): a good loan wrongly rejected
Approved (score at or above the cut-off) · False negative (FN): a bad loan wrongly approved · True negative (TN): a good loan correctly approved
This two-by-two table is the confusion matrix. The names come from calling "bad" the thing we are trying to detect, as a doctor might call "disease" the positive result. A true positive catches a bad loan. A false positive costs the lender a good customer. A false negative is a loss, since a bad loan gets through. A true negative is a good customer served.
Here is the matrix on the holdout sample at a cut-off of 560, where every borrower with a score below 560 is rejected.
· Actually bad · Actually good · TotalRejected (score below 560) · 169 · 699 · 868
Approved (score 560 or above) · 144 · 1,988 · 2,132
Total · 313 · 2,687 · 3,000
Check the totals: 169 + 144 = 313 bad loans, and 699 + 1,988 = 2,687 good loans. The cut-off rejects 868 of 3,000 applicants, 28.9 per cent.
Four measures follow from the matrix.
Sensitivity (also called the true positive rate, recall or hit rate): the share of bad loans that were rejected. TP ÷ (TP + FN) = 169 ÷ 313 = 54.0 per cent.
Specificity (the true negative rate): the share of good loans that were approved. TN ÷ (TN + FP) = 1,988 ÷ 2,687 = 74.0 per cent. Its complement, 26.0 per cent, is the false positive rate: the share of good customers wrongly rejected.
Precision: the share of rejected loans that really were bad. TP ÷ (TP + FP) = 169 ÷ 868 = 19.5 per cent.
Accuracy: the share of all loans classified correctly. (TP + TN) ÷ total = (169 + 1,988) ÷ 3,000 = 71.9 per cent.
Predict first: a lender decides to approve everybody and use no scorecard at all. What is the accuracy of "approve all", if 313 of the 3,000 loans are bad? Work it out before reading on.
Approving everyone means that every good loan is a true negative and every bad loan a false negative: accuracy = 2,687 ÷ 3,000 = 89.6 per cent. The do-nothing rule beats the scorecard at a cut-off of 560 (71.9 per cent) on accuracy, and it is useless as a risk tool. This is the accuracy trap: when one class is rare, accuracy is dominated by the common class and says nothing about the rare one. For this reason, credit risk analysts look at sensitivity and specificity, or at precision, and never at accuracy alone.
What changes with the cut-off
The cut-off is a choice, and every choice trades one kind of error for another. Raise it, and more bad loans are caught but more good customers are rejected. Here are five cut-offs on the same holdout.
Cut-off (reject below) · Rejected · Bad loans caught (TP) · Good loans rejected (FP) · Sensitivity · Specificity · Precision530 · 133 (4.4%) · 51 · 82 · 16.3% · 96.9% · 38.3%
545 · 419 (14.0%) · 107 · 312 · 34.2% · 88.4% · 25.5%
560 · 868 (28.9%) · 169 · 699 · 54.0% · 74.0% · 19.5%
575 · 1,508 (50.3%) · 228 · 1,280 · 72.8% · 52.4% · 15.1%
590 · 2,120 (70.7%) · 273 · 1,847 · 87.2% · 31.3% · 12.9%
Read across the rows. As the cut-off rises, sensitivity climbs from 16 to 87 per cent while specificity falls from 97 to 31 per cent. Precision falls too, from 38 to 13 per cent: the more you reject, the lower the share of the rejected that are really bad, since you are now reaching into the pool of better borrowers. At every cut-off, precision is low in the sense that most rejected applicants are good customers. At 560, only about one in five of those rejected would have defaulted. That is typical when the bad rate is 10 per cent. It is the reason that a scorecard cannot be judged by a single cut-off, and the reason that Lesson 7.4 chooses one by economics, not by statistics.
A single confusion matrix describes performance at one point. We need a summary of performance over all possible cut-offs. The KS statistic is one.
The KS statistic
Imagine ranking all loans from the riskiest score to the safest. Move down the list and track two running totals: the share of all bad loans seen so far (the cumulative bad rate) and the share of all good loans seen so far (the cumulative good rate). A good score puts the bad loans near the front of the list, so the cumulative share of bads rises faster than that of goods. The Kolmogorov-Smirnov statistic, or KS, is the largest gap between the two:
> KS = the maximum, over all cut-offs, of (cumulative share of bads − cumulative share of goods)
It is a number between 0 and 1, often quoted as a percentage. A KS of zero means the score does not separate the groups at all, and a KS of one would mean a perfect separation at some score.
Here is the calculation on the holdout sample, in bands of ten score points. For each band the table gives the number of loans, the number that are bad, and the cumulative percentages of all bads and all goods up to and including the band.
Score band · Loans · Bad · Bad rate · Cumulative % of bads · Cumulative % of goods · Gap510–519 · 66 · 32 · 48.5% · 10.2% · 1.3% · 9.0
520–529 · 67 · 19 · 28.4% · 16.3% · 3.1% · 13.2
530–539 · 157 · 35 · 22.3% · 27.5% · 7.6% · 19.9
540–549 · 239 · 41 · 17.2% · 40.6% · 15.0% · 25.6
550–559 · 339 · 42 · 12.4% · 54.0% · 26.0% · 28.0
560–569 · 402 · 41 · 10.2% · 67.1% · 39.4% · 27.6
570–579 · 436 · 35 · 8.0% · 78.3% · 54.4% · 23.9
580–589 · 414 · 28 · 6.8% · 87.2% · 68.7% · 18.5
590–599 · 375 · 19 · 5.1% · 93.3% · 82.0% · 11.3
600–609 · 213 · 15 · 7.0% · 98.1% · 89.4% · 8.7
610–619 · 194 · 2 · 1.0% · 98.7% · 96.5% · 2.2
620–629 · 98 · 4 · 4.1% · 100.0% · 100.0% · 0.0
The loans add to 3,000 and the bads to 313. Look at the gap column, in percentage points. It rises, peaks and falls back to zero at the end, where both cumulative figures reach 100 per cent. The peak in this ten-point table is 28.0, in the band 550 to 559. Computing the gap at every distinct score gives a slightly sharper maximum: KS = 0.285, or 28.5 per cent, reached at a score of 562, where 58.5 per cent of the bad loans and 30.0 per cent of the good loans have been rejected.
What the KS says in words: if you reject everyone with a score below about 562, you reject 58.5 per cent of all bad loans at the price of rejecting 30.0 per cent of all good loans, a difference of 28.5 points, the best separation any single cut-off can give. At other cut-offs the gap is smaller.
Two features make KS popular. It is easy to explain to a non-statistician, as the "maximum separation", and it tells you the score at which the separation is greatest. Its weakness is that it looks only at one point of the score range, and it can be insensitive to differences elsewhere. Lesson 7.2 introduces measures that use the whole curve.
What is a good KS?
There is no universal answer, because the value depends on the product, the data and the population. Credit analysts use rough guidelines for application scorecards in retail lending, which differ by lender and market.
KS · Common readingBelow 20% · Weak separation. The model adds little.
20% to 40% · Acceptable, typical of many application scorecards.
40% to 60% · Good. Typical of behavioural scorecards that use a borrower's payment history.
Above 60% to 70% · Very strong. Check for leakage or an error.
By these guidelines, the 28.5 per cent of this synthetic scorecard is acceptable for an application scorecard, which has only application and bureau data at the time of the loan and no payment history. The lower, "weak" range would be a concern. And, as in Lesson 5.3, a surprisingly high value is a prompt for suspicion: a KS above 70 per cent on a new application model usually means that something that was not known at application, such as repayment behaviour, has crept into the inputs.
A caution about samples. KS, like any statistic computed on a finite sample, has noise. With 313 bad loans, a KS of 0.285 might easily be 0.25 or 0.32 on another sample from the same population. Compare models on the same holdout, and be wary of small differences. Also remember that the KS on the development sample is higher than on the holdout, because the model has been tuned to the development data.
Reading the two tools together
The confusion matrix and the KS statistic answer different questions.
The confusion matrix is a picture at one cut-off: who is caught, who is wrongly rejected. It is the tool for the operational decision.
The KS statistic is a summary of the best separation over all cut-offs, and the score at which that occurs. It is a tool for comparing models.
A useful habit is to report both, and to say the cut-off to which any confusion matrix refers. The KS point (a score of about 562) is not necessarily the cut-off that a lender should use. It maximises the gap between the two curves, which treats a bad loan caught and a good loan lost as equally important in proportion. In lending, the two have very different costs, as Lesson 7.4 shows.
Computing both in Python
The calculation is a few lines once you have scores and outcomes.
python
import numpy as np
import pandas as pd
hold = pd.readcsv("holdoutscores.csv") # columns: score (higher = safer), bad (1/0)
def confusion(df, cutoff):
rej = df["score"] < cutoff
tp = int(((rej) & (df["bad"] == 1)).sum())
fp = int(((rej) & (df["bad"] == 0)).sum())
fn = int(((~rej) & (df["bad"] == 1)).sum())
tn = int(((~rej) & (df["bad"] == 0)).sum())
return tp, fp, fn, tn
for cut in (530, 545, 560, 575, 590):
tp, fp, fn, tn = confusion(hold, cut)
print(cut, tp, fp, fn, tn,
"sens", round(tp / (tp + fn), 3), "spec", round(tn / (tn + fp), 3),
"prec", round(tp / (tp + fp), 3), "acc", round((tp + tn) / len(hold), 3))
KS: sort from riskiest to safest, then compare cumulative shares
s = hold.sortvalues("score")
cumbad = s["bad"].cumsum() / s["bad"].sum()
cumgood = (1 - s["bad"]).cumsum() / (1 - s["bad"]).sum()
gap = (cumbad - cumgood)
print("KS =", round(gap.max(), 3), "at score", s["score"].iloc[gap.values.argmax()])
One detail: when several loans share the same score, the cumulative shares should be computed after grouping tied scores, or the gap may be slightly overstated at a point inside a group. In practice, group by score first, then take cumulative sums.
A worked example: comparing two scorecards
A lender has two candidate scorecards, A and B, tested on the same holdout of 3,000 loans with 313 bad loans. The analyst computes KS, and the confusion matrix at the approval rate the lender wants, 70 per cent (rejecting the lowest 30 per cent of scores).
· Scorecard A · Scorecard BKS · 28.5% · 31.0%
Bad loans rejected in the riskiest 30% · 172 · 178
Sensitivity at that cut-off · 55.0% · 56.9%
Precision at that cut-off · 19.1% · 19.8%
What does this say? Scorecard B has the higher KS by 2.5 points, but at the 30 per cent rejection level it catches 6 more bad loans out of 313, a difference of 1.9 percentage points of sensitivity. With only 313 bad loans, a difference of six loans is within the noise: the standard error of a sensitivity near 55 per cent from 313 bads is about 2.8 points. The analyst concludes that the evidence does not clearly favour B. She recommends checking on a larger sample, or on a later period, before choosing, and notes that if B is more complex or costly to run, A should be preferred on the present evidence. The key habit is to put the difference on the scale of the noise before acting on it.
Common mistakes
Quoting accuracy. With rare bad loans, it rewards doing nothing.
Reporting a confusion matrix without the cut-off. The numbers mean nothing without it.
Mixing up the direction. Say whether the cut-off rejects below or above, and whether positive means bad.
Using the KS point as the business cut-off. It maximises separation, not profit.
Computing KS on the development sample. It is inflated. Use a holdout.
Comparing KS values from different populations. Products, periods and bad definitions differ.
Reading small differences as real. Check the sample size.
Believing a very high KS. Above 60 to 70 per cent on an application model, look for leakage.
Key takeaways
A confusion matrix at a cut-off counts true positives, false positives, false negatives and true negatives. Sensitivity is the share of bads caught, specificity the share of goods approved and precision the share of rejects that are bad.
Accuracy is misleading when bads are rare. On the holdout, approving everyone has an accuracy of 89.6 per cent, higher than the scorecard at a cut-off of 560 (71.9 per cent).
Moving the cut-off trades error types. From a cut-off of 530 to 590, sensitivity rose from 16.3 to 87.2 per cent, while specificity fell from 96.9 to 31.3 per cent.
KS is the largest gap between the cumulative shares of bad and good loans. Here it is 28.5 per cent at a score of about 562.
A KS of 20 to 40 per cent is typical of application scorecards, and a value above 60 to 70 per cent should be checked for leakage.
Confusion matrices describe one cut-off, KS summarises the best separation, and neither alone picks the business cut-off.
Check yourself
1. At a cut-off, a lender has TP = 80, FP = 400, FN = 40 and TN = 1,480. What are the sensitivity, specificity and precision?
Sensitivity 80 ÷ 120 = 66.7 per cent. Specificity 1,480 ÷ 1,880 = 78.7 per cent. Precision 80 ÷ 480 = 16.7 per cent.
2. In the same data, what is the accuracy of approving everyone?
There are 120 bad loans out of 2,000, so approving all is right for 1,880 of 2,000, which is 94 per cent.
3. The cumulative share of bads at a score is 60 per cent and of goods is 25 per cent. What is the gap there?
35 percentage points. The KS is the largest such gap over all scores.
4. Why is the KS point not always the best cut-off for a lender?
It maximises the difference between the cumulative shares, which treats the two errors as equally costly in proportion. A bad loan usually costs much more than a lost good loan earns.
5. A new application scorecard shows a KS of 75 per cent. What should you do?
Suspect leakage or a data error, such as an input that includes information from after the application. Check each input's timing before accepting the result.
Try this
Measure a scorecard on a holdout of your own. Set aside forty to fifty minutes.
1. Take the scores and outcomes of a holdout sample, from Module 6 or invented: at least 2,000 loans with about 10 per cent bad and a score where higher means safer.
2. Pick three cut-offs. For each, build the confusion matrix, writing the four counts and checking that they add to the totals.
3. Compute sensitivity, specificity, precision and accuracy for each cut-off. Compare the accuracy with that of approving everyone.
4. Group the loans into score bands of equal width, ten or twelve of them. Compute the cumulative percentage of bads and goods and the gap for each band.
5. Find the largest gap, the KS, and the score at which it occurs. Chart the two cumulative curves.
6. Use the simulator to check one of your confusion matrices, and note which measure changes most when you move a cell by 20.
7. Write a four-sentence note for a model reviewer: the KS and its score, what the three cut-offs show about the trade-off, why accuracy was not used and one reason to be cautious about the numbers.
A good result is three confusion matrices with their measures, a cumulative table with a clear peak, a KS you can locate on the score scale and a note that explains the trade-off. Lesson 7.2 moves from the single largest gap to measures that use the whole curve: the CAP curve, the Gini coefficient and the area under the ROC curve.
Tags: Credit Risk Analytics Confusion Matrix KS Statistic Model Performance Scorecard Validation