Lesson 7.5: Calibration and PD back-testing
Test whether predicted PDs match observed default rates with decile tables, binomial tests, Hosmer-Lemeshow and traffic lights, then recalibrate if needed.
By the end of this lesson you will be able to test whether the probabilities of default that a model produces are right, which is a different question from whether the model ranks borrowers well. You will build a calibration table that compares predicted and observed default rates by group, test each group with a binomial test and the whole table with a Hosmer-Lemeshow statistic, summarise the result in a traffic-light report, see on a worked example how a model can keep its ranking power and still be badly miscalibrated, find the likely causes, and fix the problem by recalibrating with a simple shift of the log odds. You should have read Lessons 7.1 to 7.4, which measured ranking, and Lesson 6.2, which turned the model into a score and a PD. The arithmetic is expected counts, standard deviations and a little statistics, and every figure comes from calculations on the holdout sample used in this module.
Lessons 7.1 to 7.3 measured discrimination: does the model put the bad loans on the risky side of the list? That is only half of what a lender needs. A lender also relies on the level of the probabilities, since they feed provisions, pricing, capital and the cut-off economics of Lesson 7.4. A model that ranks perfectly but says that the average PD is 5 per cent when it is really 10 per cent will approve loans that lose money, hold too little capital and understate provisions. Checking that the predicted probabilities match reality is called calibration, and checking it against outcomes after the fact is called back-testing.
Discrimination and calibration are different
A short example makes the difference clear. Suppose every PD in a model is exactly twice the true figure: where the truth is 2 per cent the model says 4, where it is 10 the model says 20. The ranking is unchanged, since the order of borrowers is the same, so the AUC and Gini are perfect for whatever the true model's were. But the PDs are all wrong, and every number computed from them (expected loss, provisions, the break-even) is wrong by the same factor.
The reverse also exists. A model that gave every borrower the same PD, equal to the overall default rate, would be perfectly calibrated at the portfolio level (the average is right) and would have no discriminating power at all (AUC 0.5). Good models need both: a correct order and correct levels. Each is tested separately.
· Ranking (discrimination) · Levels (calibration)Question · Are the bad loans ranked as riskier? · Is the predicted PD close to the observed default rate?
Tools · AUC, Gini, KS · Calibration table, binomial test, Hosmer-Lemeshow, Brier score
Fixed by · Rebuilding the model · Recalibrating the scale
Needed for · Selection and cut-offs · Provisions, pricing, capital
## The calibration table
The basic tool is a table that groups the loans by predicted PD and compares the average prediction in each group with the share that actually defaulted. Sort the 3,000 holdout loans by the model's predicted PD, and cut them into ten groups of 300, the deciles. For each decile, record the mean predicted PD, the number of bad loans that were expected (the PD times 300) and the number that were observed.
Decile · Mean predicted PD · Expected bad loans · Observed bad loans · Observed default rate1 (safest) · 1.87% · 5.6 · 8 · 2.67%
2 · 2.99% · 9.0 · 17 · 5.67%
3 · 4.04% · 12.1 · 16 · 5.33%
4 · 5.21% · 15.6 · 17 · 5.67%
5 · 6.60% · 19.8 · 27 · 9.00%
6 · 8.20% · 24.6 · 28 · 9.33%
7 · 10.18% · 30.5 · 28 · 9.33%
8 · 13.02% · 39.1 · 38 · 12.67%
9 · 17.49% · 52.5 · 46 · 15.33%
10 (riskiest) · 28.82% · 86.4 · 88 · 29.33%
Total · · 295.2 · 313 ·
Look at the two columns, the expected and the observed counts. The pattern is reasonably good: the observed default rate rises steadily, from 2.7 per cent in the safest decile to 29.3 per cent in the riskiest, and is close to the prediction at the risky end (88 observed against 86.4 expected). In the safer half, the model's predictions run a little low: the observed counts exceed the expected ones in deciles 1 to 6. In total, 313 bad loans were observed against 295.2 expected, an excess of 6 per cent.
The plot is the fastest way to see calibration. A perfectly calibrated model would put the two lines on top of each other. A line that sits above the other shows under-prediction, and one that sits below it shows over-prediction. A gap that widens with risk, such as the observed line being steeper than the predicted one, signals a slope problem as well as a level problem.
Testing one group: the binomial test
How far apart must the lines be before we should worry? Each decile contains only 300 loans, and the number of defaults in a group of 300 is random: even if the PD is exactly right, the observed count will not equal the expected one. The right question is whether the observed count is unlikely if the PD is correct.
If every loan in a group has a probability p of default, and defaults are independent, the number of defaults follows a binomial distribution with mean n × p and standard deviation the square root of n × p × (1 − p). For a group with n = 300 and p = 2.99 per cent (decile 2):
Expected: 300 × 0.0299 = 8.97, or about 9.0.
Standard deviation: the square root of 300 × 0.0299 × 0.9701 = the square root of 8.70 = 2.95.
Observed: 17.
z-score = (17 − 8.97) ÷ 2.95 = +2.73.
A z-score measures how many standard deviations the observed count lies above the expected. About 95 per cent of the time, a correctly calibrated group falls within 1.96 standard deviations of the expected count (in either direction), and 99.7 per cent of the time within 3. So a z-score of 2.73 is unusual: this would happen less than one time in a hundred if the PD were right. But we have tested ten groups, and with ten tests, one result beyond 2 is not surprising.
Predict first: in the holdout table, decile 2 has a z-score of +2.73 and no other decile exceeds 1.7. Is that evidence that the model is badly calibrated? Think about how many groups were tested before reading on.
On its own, no. With ten groups, you expect about one in twenty to fall outside plus or minus 1.96 by chance, so about half a group in ten. One group at 2.73 is a little more than chance would usually give, and it deserves a look, but it is not enough to condemn the model. What matters more is the overall pattern: here, nine of ten deciles have observed counts at or above the expected in the safer half, which suggests a modest, systematic under-prediction of about 6 per cent, in line with the total (313 against 295.2).
With the defaults, the observed 17 is above the 95 per cent bound of 13.8 and below the 99.9 per cent bound of 18.1: amber. Move the observed count to 19 and it turns red. Move the group size to 3,000 loans with the same predicted PD and a 5.67 per cent observed rate (170 bad loans), and the verdict becomes decisively red: larger groups have narrower bounds, so the same gap in rate means more.
Testing the whole table: Hosmer-Lemeshow
To test all ten groups together, add up the squared z-scores. The Hosmer-Lemeshow statistic is:
> HL = the sum, over groups, of (observed − expected)² ÷ (n × p × (1 − p))
where n and p are the size and the mean predicted PD of each group. Under the hypothesis that the model is calibrated, it follows a chi-squared distribution with (number of groups − 2) degrees of freedom, here 8. Larger values mean worse calibration. The 5 per cent critical value for 8 degrees of freedom is 15.51.
For the holdout table the statistic is 14.49, with a probability of about 7 per cent. It is below the critical value, so the model passes, narrowly. The conclusion is cautious: the data are compatible with a calibrated model, and the overall excess of 6 per cent suggests keeping an eye on the safer deciles. The test is also imprecise at the edges: with a small sample it has little power, and with a very large sample it flags tiny, harmless differences. It is a screen and not a verdict.
The Brier score, met in Lesson 4 of the Decision Making track, provides another summary of the quality of probabilities. For the holdout sample it is 0.0876, against 0.0934 for a model that gives every loan the portfolio average of 10.4 per cent. The model improves on the baseline by about 6 per cent. The Brier score blends discrimination and calibration, so it is more a summary of usefulness than a diagnostic.
A back-test over time: ranking holds, levels drift
The holdout test checks the model on loans from the same period as the development data. Back-testing in production checks it later, on the loans that were scored at one date and followed for a year. Models often fail here because the world has changed.
To illustrate, suppose a new cohort of 3,000 applicants arrives a year later, in a weaker economy. They are scored by the same model, with the same ranking, and the predicted PDs look the same as before. But in reality the log odds of default of every borrower are 0.35 higher than the model believes, a shift typical of a downturn. (The cohort is simulated by resampling the holdout loans and drawing outcomes from the shifted probabilities, so the numbers are synthetic and exact in their construction.)
Decile · Mean predicted PD · Expected bad loans · Observed bad loans · Observed default rate · z-score1 · 1.85% · 5.6 · 7 · 2.33% · 0.62
2 · 2.94% · 8.8 · 10 · 3.33% · 0.40
3 · 3.93% · 11.8 · 17 · 5.67% · 1.55
4 · 5.03% · 15.1 · 19 · 6.33% · 1.04
5 · 6.31% · 18.9 · 32 · 10.67% · 3.10
6 · 7.85% · 23.5 · 35 · 11.67% · 2.46
7 · 10.02% · 30.1 · 47 · 15.67% · 3.26
8 · 13.03% · 39.1 · 60 · 20.00% · 3.59
9 · 17.25% · 51.8 · 72 · 24.00% · 3.09
10 · 28.22% · 84.7 · 100 · 33.33% · 1.97
Total · · 289.3 · 399 · ·
The table tells a clear story. The model expected 289.3 bad loans and 399 occurred, a ratio of 1.38. In the middle deciles, 5 to 9, the z-scores are all above 2.4, and deciles 5, 7, 8 and 9 exceed 3. The Hosmer-Lemeshow statistic is 56.6, far beyond the critical value of 15.51. The total count is more than 7 standard deviations above the expectation (z = 7.0). The model has failed its calibration test.
And yet the ranking is intact: the AUC on this cohort is 0.728, as good as before. The model still puts the riskier borrowers where it should. This is typical of a macroeconomic shift: everyone becomes riskier by about the same factor, and the order of borrowers stays the same while the levels drift. A lender that watched only the AUC or Gini would see nothing wrong and underprovision by a third.
Traffic lights. A back-test report summarises each group with a colour.
Decile · Expected · Observed · 95% bound · 99.9% bound · Colour2 · 8.8 · 10 · 13.6 · 17.9 · Green
5 · 18.9 · 32 · 25.9 · 31.9 · Red
8 · 39.1 · 60 · 48.7 · 57.1 · Red
10 · 84.7 · 100 · 97.5 · 108.7 · Amber
Decile 8, for example, has an expected count of 39.1 and a standard deviation of 5.83. The 95 per cent upper bound is 39.1 + 1.645 × 5.83 = 48.7, and the 99.9 per cent bound is 39.1 + 3.09 × 5.83 = 57.1. The 60 observed bad loans exceed even the higher bound. Reds and ambers trigger a review and, if confirmed, a recalibration or a rebuild.
Why calibration drifts
Several things can move observed default rates away from the predictions.
The economic cycle. A model calibrated in a boom will under-predict in a recession, and the reverse. A point-in-time PD tracks the current conditions and moves with the cycle. A through-the-cycle PD averages across it and should be stable. Say which one the model is meant to be, and test accordingly.
A change in the population. New channels, products or regions bring borrowers that the model did not see in development.
A change in policy. A tighter cut-off changes who is approved and therefore who is observed to default.
A change in definitions. If the lender redefines default or changes collections, the outcome that the model was trained to predict is no longer the one being measured.
Fraud, data changes or a broken input. A feed that stops, or a field whose meaning changes, can alter scores without any change in risk.
Growth. A fast-growing book has many young loans whose default rates change as they season, as Lesson 4.3 showed.
Small samples. With few defaults, observed rates are noisy, so be careful about acting on one quarter of data.
Finding the cause matters, because the remedy depends on it: a cycle shift calls for a recalibration, a broken data feed for a repair and a population change for a rebuild.
Recalibration
When the ranking is sound and the levels are off, the usual fix is to recalibrate: keep the model and adjust the mapping from score to PD. The simplest form is a shift of the log odds by a constant.
In the later cohort, the shift that makes the total of the predicted PDs equal the observed 399 defaults is about +0.395 on the log odds of default. (It is close to the 0.35 used to build the cohort, the difference being sampling noise.) In terms of odds, this multiplies the odds of default by e^0.395 = 1.48, which divides the odds of good to bad by 1.48.
Apply it to the score-to-PD mapping of Lesson 6.2:
Score · Odds of good before · PD before · Odds of good after (divided by 1.48) · PD after540 · 3.75 · 21.1% · 2.53 · 28.4%
580 · 15 · 6.3% · 10.10 · 9.0%
620 · 60 · 1.6% · 40.4 · 2.4%
A richer recalibration fits a small logistic regression of the outcome on the log odds of the model's PD, which gives a calibration intercept (the level shift) and a calibration slope (whether the model is too steep or too flat). A slope near 1 and an intercept near 0 mean the model is well calibrated. A slope below 1 means the predictions are too spread out, with the risky too risky and the safe too safe, which is common for models that are overfitted.
Recalibration is cheap, but it is not a cure-all. It corrects the level and not the ranking. If the AUC has fallen, or the population has changed, a rebuild is required. And a recalibration to a downturn level will over-predict when the economy recovers, so many lenders keep a long-run calibration for capital and pricing and a current one for provisioning. All changes go through model governance, with documentation and approval.
A monitoring routine
A sound back-testing routine for a PD model has these parts.
1. Frequency. Quarterly for most retail models, monthly for fast-moving portfolios, with a full annual review.
2. Portfolio level. Compare the total expected and observed defaults, with a binomial test.
3. Group level. Compare by decile or by rating grade with a traffic-light summary, and look at the pattern as well as individual groups.
4. Discrimination. Track the AUC or Gini and the KS on each new cohort, with a range for the noise.
5. Stability of inputs. Check that the score distribution and the characteristics have not shifted (Module 8 covers the population stability index).
6. Thresholds and escalation. Agree in advance what triggers what: for example, an amber result is noted, two ambers in a row trigger investigation and a red triggers a recalibration decision within a month.
7. Documentation. Record the tests, the results and the decisions.
Most of it can be automated, and the value is in having the thresholds fixed before the data arrive, so that nobody can argue them down when the result is uncomfortable.
Calibration in Python
The calibration table, the tests and the recalibration take a few lines.
python
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy import stats
df = pd.readcsv("cohort.csv") # columns: pd (model PD), bad (1/0)
df["decile"] = pd.qcut(df["pd"], 10, labels=False) + 1
g = df.groupby("decile").agg(n=("bad", "size"), pdmean=("pd", "mean"), bads=("bad", "sum"))
g["expected"] = g["n"] g["pdmean"]
g["sd"] = np.sqrt(g["n"] g["pdmean"] (1 - g["pdmean"]))
g["z"] = (g["bads"] - g["expected"]) / g["sd"]
g["u95"] = g["expected"] + 1.645 g["sd"]
g["u999"] = g["expected"] + 3.09 g["sd"]
g["colour"] = np.where(g["bads"] > g["u999"], "red", np.where(g["bads"] > g["u95"], "amber", "green"))
print(g.round(2))
Hosmer-Lemeshow
hl = (((g["bads"] - g["expected"]) 2) / (g["n"] g["pdmean"] (1 - g["pdmean"]))).sum()
print("HL", round(hl, 2), "p =", round(1 - stats.chi2.cdf(hl, df=len(g) - 2), 4))
Brier score against the portfolio-average baseline
brier = ((df["pd"] - df["bad"]) 2).mean()
base = df["bad"].mean() (1 - df["bad"].mean())
print("Brier", round(brier, 4), "baseline", round(base, 4))
recalibration: logistic regression of the outcome on the log odds of the PD
logit = np.log(df["pd"] / (1 - df["pd"]))
cal = sm.Logit(df["bad"], sm.addconstant(logit)).fit(disp=0)
print("calibration intercept", round(cal.params["const"], 3), "slope", round(cal.params["pd"], 3))
shift-only recalibration: find a so that the mean recalibrated PD equals the observed rate
def shiftedmean(a):
return (1 / (1 + np.exp(-(logit + a)))).mean()
lo, hi = -2, 2
for in range(60):
mid = (lo + hi) / 2
lo, hi = (mid, hi) if shiftedmean(mid) < df["bad"].mean() else (lo, mid)
print("shift", round((lo + hi) / 2, 3))
Keep the thresholds in code, so that a back-test is the same each quarter. Print the n beside each group, since small groups make large z-scores unlikely and weak tests.
A worked example: reporting to a committee
A risk committee meets after the back-test of the later cohort. The analyst's note has four parts.
1. What happened. The model expected 289 defaults and 399 occurred, 38 per cent more. The AUC is 0.728, unchanged. Three deciles are red and a fourth sits on the red line.
2. Diagnosis. Ranking is intact, so the model still sorts borrowers correctly. The level has shifted by about +0.4 on the log odds, consistent with a deterioration in the economy. The bad rate rose in every decile above the second, and the gap is widest in the middle, where most of the approvals lie.
3. Consequences. Provisions based on the old PDs are about 28 per cent too low (289 ÷ 399 = 72 per cent). The cut-off of 570 now has a marginal bad rate above the break-even, so it is approving loans that lose money, as in Lesson 7.4.
4. Recommendation. Apply a recalibration shift of +0.395 for provisioning from this quarter, raise the cut-off by about 10 to 20 points pending a review of the economics, keep the model's ranking, monitor monthly and rebuild if the AUC falls or the shift does not reverse within two quarters.
The committee asks one question: "Is this a model failure?" The analyst answers that the model ranks well and its level has been overtaken by events, which is a recalibration issue and not a rebuild issue, and that the risk would have been missed if only the Gini had been monitored. That one answer justifies the whole back-testing process.
Common mistakes
Judging a model by AUC alone. Check the levels as well.
Testing only the portfolio total. Errors in different groups can cancel.
Over-reacting to one group out of ten. Look at the pattern across groups and allow for multiple tests.
Ignoring the group size. Small groups give noisy rates and weak tests.
Forgetting that defaults cluster. A recession affects many borrowers together, so the binomial test, which assumes independence, will flag too often. Allow for correlation in formal tests.
Recalibrating without diagnosing. A level shift from a downturn, a broken feed and a population change need different responses.
Mixing point-in-time and through-the-cycle. Test each against the right target.
Changing thresholds after seeing the result. Fix them in advance.
Key takeaways
Calibration asks whether predicted PDs match observed default rates, and it is separate from ranking power. A model can rank perfectly and be badly calibrated.
A calibration table compares the mean predicted PD with the observed default rate by decile or grade. On the holdout, 313 bad loans were observed against 295.2 expected.
The binomial test gives a z-score for each group: (observed − expected) ÷ the square root of n × p × (1 − p). A traffic light compares the count with upper bounds at 95 and 99.9 per cent.
The Hosmer-Lemeshow statistic sums the squared z-scores over groups. On the holdout it was 14.5 against a critical 15.5 (pass). On the later cohort it was 56.6 (fail).
In the later cohort, defaults were 38 per cent above prediction (399 against 289) while the AUC stayed at 0.728. Monitoring the Gini alone would have missed it.
Recalibrate with a log-odds shift (here about +0.395, which multiplies the odds of default by 1.48), after diagnosing the cause. The ranking is unchanged.
Decide thresholds and escalation in advance, and back-test on a regular schedule.
Check yourself
1. A grade has 400 loans, a predicted PD of 5 per cent and 31 observed defaults. What is the z-score?
Expected 20, standard deviation sqrt(400 × 0.05 × 0.95) = 4.36, z = (31 − 20) ÷ 4.36 = 2.52.
2. Why can a model have a high AUC and fail a calibration test?
The AUC measures only the order of borrowers. If every PD is too low by the same factor, the order is right and the levels are wrong.
3. A back-test table with ten groups has a Hosmer-Lemeshow value of 22. The 5 per cent critical value for 8 degrees of freedom is 15.5. What does this mean?
The value is above the critical value, so the model fails the calibration test. Look at which groups drive it and investigate the cause.
4. Predicted PDs in a cohort sum to 200 defaults and 260 are observed. By what factor do the odds of default need to move, roughly?
Roughly 1.3 for small PDs, since odds are close to probabilities. A logistic recalibration finds the precise shift.
5. Name two causes of a calibration failure that recalibration will not cure.
A broken data feed and a major change in the borrower population or in the definition of default. These need repair or a rebuild.
Try this
Back-test a model of your own. Set aside forty to fifty minutes.
1. Take predicted PDs and outcomes for a cohort of at least 2,000 loans, from Module 6 or invented. If you invent them, build a second cohort in which risk is shifted up.
2. Sort by predicted PD and cut into ten groups. Build a calibration table with the mean PD, the expected and observed counts and the observed rate. Draw the two lines.
3. Compute the standard deviation and the z-score of each group. Mark the groups beyond the 95 and 99.9 per cent bounds, and assign traffic-light colours with the simulator pattern.
4. Compute the Hosmer-Lemeshow statistic and compare it with the critical value for eight degrees of freedom, 15.51.
5. Compute the AUC of the cohort and compare it with the development value. Write one sentence on whether the problem is ranking or levels.
6. Find the log-odds shift that makes the predicted total equal the observed total. Apply it to the PDs at three scores and tabulate the change.
7. Write a five-sentence note for a risk committee: what the back-test found, which groups failed, whether the ranking is intact, your recommendation and the trigger that would lead you to rebuild instead.
A good result is a calibration table with expected and observed counts, a traffic-light summary, a Hosmer-Lemeshow figure, a recalibration shift and a note that separates ranking from levels. This completes the module on performance. Module 8 moves from measuring a model once to watching it over time: validation techniques, population stability and monitoring.
Tags: Credit Risk Analytics Calibration Back-testing Binomial Test Model Monitoring