Calibration#
Check and correct predicted probabilities. prior_correction() and corrected_intercept() correct them for the sampling of the development data, master_scale(), fit_grade_pd() and assign_grades() build a master scale and assign its grades, calibration_table() and the tests count and test the grades, and platt_fit() and isotonic_fit() recalibrate a score. spiegelhalter_test() and brier_decomposition() check the probabilities of single observations, concentration_test() tests the concentration of the grades, and backtest_table() back-tests continuous estimates such as LGDs.
See Calibration for examples on the bundled data, and Model validation for the tests of a validation report.
|
Correct event probabilities for a development sample with another event rate. |
|
Correct a logistic intercept for a development sample with another event rate. |
|
Compare the predicted and observed event rates of each group. |
|
Test whether each grade has more events than its probability predicts. |
|
Test each grade's probability against its event rate with the Jeffreys prior. |
|
Test the calibration of all groups at once with the Hosmer-Lemeshow statistic. |
|
Test the calibration of individual probabilities with Spiegelhalter's z statistic. |
|
Split the Brier score into reliability, resolution, uncertainty and two within-group terms. |
|
Measure how concentrated a portfolio is across grades. |
|
Test whether the grades of a rating scale are more concentrated than at development. |
|
Back-test continuous estimates, such as LGDs or CCFs, against realized values. |
|
Build a master scale from the PD of each grade. |
|
Fit the PD of each grade to observed default rates, log-linear in the grade. |
|
Give each predicted PD the grade of a master scale. |
|
Fit Platt scaling, a logistic curve from a score to event probabilities. |
|
Turn scores into event probabilities with a fitted Platt scaling. |
|
Fit an isotonic calibration, a step function from a score to event probabilities. |
|
Give each score the probability of its band from an isotonic calibration. |
- kivi.calibration.prior_correction(probability, *, sample_rate, population_rate)#
Correct event probabilities for a development sample with another event rate.
A model developed on a sample that over- or undersamples events predicts probabilities for that sample. The correction rescales the odds so the probabilities refer to the population.
- Parameters:
- probabilityarray_like
Event probabilities from the model, between 0 and 1. Missing values stay missing.
- sample_ratefloat
Event rate of the development sample, strictly between 0 and 1.
- population_ratefloat
Event rate of the population, strictly between 0 and 1.
- Returns:
- float, pandas.Series or numpy.ndarray
Corrected probabilities with the shape of probability. A Series input gives a Series with the same index and name, and a scalar gives a float.
- Raises:
- ValueError
If probability has values outside [0, 1], or a rate is not strictly between 0 and 1.
See also
corrected_interceptApply the same correction to a logistic intercept.
calibration_tableCompare predicted and observed event rates.
Notes
With sample event rate \(\bar y\) and population event rate \(\tau\), the odds of every probability are multiplied by
\[\omega = \frac{\tau / (1 - \tau)}{\bar y / (1 - \bar y)}, \qquad \tilde p = \frac{\omega p}{\omega p + 1 - p}.\]This is the prior correction of King and Zeng [1]. It changes the level of the probabilities but not their order. For a logistic regression it equals adding \(\ln \omega\) to the intercept.
References
[1]G. King and L. Zeng, “Logistic Regression in Rare Events Data”, Political Analysis, vol. 9, no. 2, pp. 137-163, 2001.
Examples
>>> from kivi.calibration import prior_correction >>> prior_correction([0.5, 0.2, 0.05], sample_rate=0.5, population_rate=0.02).round(4) array([0.02 , 0.0051, 0.0011])
- kivi.calibration.corrected_intercept(intercept, *, sample_rate, population_rate)#
Correct a logistic intercept for a development sample with another event rate.
The corrected model gives the probabilities of prior_correction: only the intercept changes, so the coefficients and the order of applicants stay as they are.
- Parameters:
- interceptfloat
Intercept of a logistic regression of the event.
- sample_ratefloat
Event rate of the development sample, strictly between 0 and 1.
- population_ratefloat
Event rate of the population, strictly between 0 and 1.
- Returns:
- float
The intercept for the population,
intercept + ln(omega).
- Raises:
- ValueError
If intercept is not a finite number, or a rate is not strictly between 0 and 1.
See also
prior_correctionApply the correction to probabilities.
Notes
King and Zeng [1] subtract \(\ln\left[\frac{1 - \tau}{\tau} \cdot \frac{\bar y}{1 - \bar y}\right] = -\ln \omega\) from the intercept; see prior_correction.
References
[1]G. King and L. Zeng, “Logistic Regression in Rare Events Data”, Political Analysis, vol. 9, no. 2, pp. 137-163, 2001.
Examples
>>> from kivi.calibration import corrected_intercept >>> print(f"{corrected_intercept(0.0, sample_rate=0.5, population_rate=0.02):.4f}") -3.8918
- kivi.calibration.calibration_table(groups, target, probability, *, weights=None)#
Compare the predicted and observed event rates of each group.
The groups are typically the grades of a master scale, formed by cutting the probabilities at fixed edges, or score bands. Each row has the inputs of the calibration tests.
- Parameters:
- groupsarray_like
Grade or group labels. Missing values form a group.
- targetarray_like
Binary labels, with 1 indicating the event. A group, or the whole sample, may have no events.
- probabilityarray_like
Predicted event probabilities between 0 and 1. Series inputs must have identical indices; otherwise the inputs are matched by position.
- weightsarray_like, optional
Non-negative weight of each observation, such as the inverse of its sampling rate, matched like target.
totalandeventare then sums of weights, the rate and the mean probability are weighted, and groups whose weights sum to zero are left out.
- Returns:
- pandas.DataFrame
One row per group with the number of observations
total, the number of eventsevent, the observedevent_rateand the mean predicted probabilitymean_probability.
- Raises:
- ValueError
If the inputs are not one-dimensional, are empty, or their indices or lengths do not match, target has labels other than 0 and 1, or probability has missing values or values outside [0, 1]. Also if weights is not numeric, does not give each observation one finite, non-negative weight with a positive total, or has an index other than that of groups.
See also
binomial_testTest whether a grade has more events than predicted.
jeffreys_testThe Bayesian counterpart of the binomial test.
hosmer_lemeshowTest the calibration of all groups at once.
herfindahl_indexMeasure how concentrated the grades are.
Notes
Groups are counted as in kivi.woe.woe_table. Rows follow the order of the categories when groups is categorical, such as the result of
pandas.cut, with missing values last. Otherwise they follow the order in which the groups first appear. Categories that are never observed are omitted.The binomial, Jeffreys and Hosmer-Lemeshow tests need whole numbers of observations and events, so run them on an unweighted table.
Examples
>>> import pandas as pd >>> from kivi.calibration import calibration_table >>> grades = pd.Series(["A", "A", "B", "B", "B"]) >>> target = pd.Series([0, 0, 0, 1, 1]) >>> probability = pd.Series([0.1, 0.2, 0.3, 0.4, 0.5]) >>> calibration_table(grades, target, probability) total event event_rate mean_probability bin A 2 0 0.000000 0.15 B 3 2 0.666667 0.40
- kivi.calibration.binomial_test(event, total, probability)#
Test whether each grade has more events than its probability predicts.
The one-sided exact binomial test assumes independent events. A small p-value means that the probability underestimates the event rate of the grade.
- Parameters:
- eventarray_like
Number of events in each grade.
- totalarray_like
Number of observations in each grade, a positive whole number.
- probabilityarray_like
Predicted event probability of each grade, between 0 and 1, such as the
mean_probabilitycolumn of calibration_table. The three inputs are broadcast together; Series inputs must have identical indices.
- Returns:
- float, pandas.Series or numpy.ndarray
One-sided p-values: a Series with the index of the Series inputs, a float for scalar inputs and an array otherwise.
- Raises:
- ValueError
If the inputs cannot be broadcast or their Series indices differ, total is not a positive whole number, event is not a whole number between 0 and total, or probability is outside [0, 1].
See also
jeffreys_testThe Bayesian counterpart of this test.
calibration_tableThe counts and predicted probabilities of each grade.
Notes
Under the null hypothesis the number of events \(D\) among \(N\) observations follows a binomial distribution with probability \(p\). The p-value is
\[P(D \ge d) = \sum_{k=d}^{N} \binom{N}{k} p^k (1 - p)^{N - k} = I_p(d, N - d + 1),\]with the regularized incomplete beta function \(I\), and 1 when \(d = 0\). Correlated defaults, as in an economic downturn, make the test reject more often than its nominal level [1].
References
[1]Basel Committee on Banking Supervision, “Studies on the Validation of Internal Rating Systems”, Working Paper No. 14, 2005.
Examples
>>> from kivi.calibration import binomial_test >>> binomial_test([0, 3, 8], [200, 200, 200], 0.02).round(4) array([1. , 0.7649, 0.0493])
- kivi.calibration.jeffreys_test(event, total, probability)#
Test each grade’s probability against its event rate with the Jeffreys prior.
The p-value is the posterior probability that the true event rate is at most the predicted probability. A small p-value means that the probability underestimates the event rate of the grade.
- Parameters:
- eventarray_like
Number of events in each grade.
- totalarray_like
Number of observations in each grade, a positive whole number.
- probabilityarray_like
Predicted event probability of each grade, between 0 and 1, such as the
mean_probabilitycolumn of calibration_table. The three inputs are broadcast together; Series inputs must have identical indices.
- Returns:
- float, pandas.Series or numpy.ndarray
One-sided p-values: a Series with the index of the Series inputs, a float for scalar inputs and an array otherwise.
- Raises:
- ValueError
If the inputs cannot be broadcast or their Series indices differ, total is not a positive whole number, event is not a whole number between 0 and total, or probability is outside [0, 1].
See also
binomial_testThe frequentist counterpart of this test.
calibration_tableThe counts and predicted probabilities of each grade.
Notes
With the Jeffreys prior Beta(1/2, 1/2), the posterior of the event rate after \(d\) events among \(N\) observations is \(\mathrm{Beta}(d + 1/2, N - d + 1/2)\), and the p-value is its distribution function at the predicted probability \(p\):
\[I_p\left(d + \tfrac12, N - d + \tfrac12\right).\]This is the test that the European Central Bank asks for in the validation of PD models [1]. Unlike the binomial test, a grade without events still has a p-value below 1.
References
[1]European Central Bank, “Instructions for reporting the validation results of internal models: IRB Pillar I models for credit risk”, 2019.
Examples
>>> from kivi.calibration import jeffreys_test >>> jeffreys_test([0, 3, 8], [200, 200, 200], 0.02).round(4) array([0.9956, 0.6701, 0.032 ])
- kivi.calibration.hosmer_lemeshow(event, total, probability, *, ddof=2)#
Test the calibration of all groups at once with the Hosmer-Lemeshow statistic.
The statistic adds up the squared differences between observed and predicted events of each group. A small p-value means that the probabilities do not match the observed event rates.
- Parameters:
- eventarray_like
Number of events in each group.
- totalarray_like
Number of observations in each group, a positive whole number.
- probabilityarray_like
Mean predicted event probability of each group, strictly between 0 and 1, such as the
mean_probabilitycolumn of calibration_table. Series inputs must have identical indices.- ddofint, default 2
The chi-square distribution has as many degrees of freedom as there are groups, minus ddof.
- Returns:
- statisticfloat
The Hosmer-Lemeshow statistic.
- pvaluefloat
Its upper tail probability under the chi-square distribution.
- Raises:
- ValueError
If the inputs are not one-dimensional, have different lengths or Series indices, total is not a positive whole number, event is not a whole number between 0 and total, probability is not strictly between 0 and 1, or ddof is negative or leaves no degree of freedom.
See also
calibration_tableThe counts and predicted probabilities of each group.
binomial_testTest each grade on its own.
Notes
For \(g\) groups with \(d_k\) events among \(n_k\) observations and mean predicted probability \(\bar p_k\),
\[H = \sum_{k=1}^{g} \frac{(d_k - n_k \bar p_k)^2}{n_k \bar p_k (1 - \bar p_k)},\]compared with a chi-square distribution with \(g - \mathrm{ddof}\) degrees of freedom. Hosmer and Lemeshow [1] form about ten groups of similar size from the sorted probabilities of the sample the model was fitted on, which gives \(g - 2\). For probabilities that were not fitted on the tested sample, such as a validation sample, use
ddof=0[2].References
[1]D. W. Hosmer and S. Lemeshow, “Goodness of fit tests for the multiple logistic regression model”, Communications in Statistics - Theory and Methods, vol. 9, no. 10, pp. 1043-1069, 1980.
[2]D. W. Hosmer, S. Lemeshow and R. X. Sturdivant, “Applied Logistic Regression”, 3rd ed., Wiley, 2013.
Examples
>>> from kivi.calibration import hosmer_lemeshow >>> statistic, pvalue = hosmer_lemeshow([2, 6, 15], [100, 100, 100], [0.03, 0.06, 0.12]) >>> print(f"statistic = {statistic:.3f}, pvalue = {pvalue:.3f}") statistic = 1.196, pvalue = 0.274
- kivi.calibration.spiegelhalter_test(probability, target, *, weights=None)#
Test the calibration of individual probabilities with Spiegelhalter’s z statistic.
The test compares the Brier score of the probabilities with the score they would have if they were the true event probabilities. Unlike the tests of grouped counts, it needs no groups. A small p-value means that the probabilities do not match the outcomes, in either direction.
- Parameters:
- probabilityarray_like
Predicted event probability of each observation, between 0 and 1.
- targetarray_like
Binary labels, with 1 indicating the event. The sample may have no events. If probability and target are both pandas Series, they must have identical indices; otherwise they are matched by position.
- weightsarray_like, optional
Non-negative frequency weight of each observation, matched like target: integer weights give the same result as repeating rows.
- Returns:
- statisticfloat
The z statistic, approximately standard normal when the probabilities are the true ones. It is positive when the Brier score of the probabilities exceeds its expectation under them, and negative when it falls short of it. When every probability is below 1/2, as PDs usually are, a positive statistic means more events than the probabilities predict and a negative one fewer; both reject the probabilities.
- pvaluefloat
Its two-sided p-value.
- Raises:
- ValueError
If the inputs are empty or not one-dimensional, their indices or lengths do not match, target has a label other than 0 and 1, or probability is not real and numeric, has a missing value or a value outside [0, 1]. Also if weights is not numeric, does not give each observation one finite, non-negative weight with a positive total, or has an index other than that of probability.
See also
hosmer_lemeshowTest grouped counts against their mean probabilities.
brier_decompositionSplit the Brier score into calibration and resolution.
kivi.metrics.brier_scoreThe Brier score itself.
Notes
For probabilities \(p_i\) and outcomes \(y_i\) of \(N\) observations, the Brier score \(B = \sum_i (y_i - p_i)^2 / N\) has the expectation \(\sum_i p_i (1 - p_i) / N\) and the variance \(\sum_i (1 - 2 p_i)^2 p_i (1 - p_i) / N^2\) when each \(y_i\) is an independent Bernoulli draw with probability \(p_i\). Spiegelhalter [1] standardizes the score with them:
\[z = \frac{\sum_i (y_i - p_i)(1 - 2 p_i)} {\sqrt{\sum_i (1 - 2 p_i)^2 \, p_i (1 - p_i)}},\]and the p-value is \(2 (1 - \Phi(|z|))\). With weights, every sum weighs its terms with the weights of the observations.
The denominator is 0 when every probability is 0, 1/2 or 1.
zis then infinite, with a p-value of 0, when an event has a probability of 0 or a non-event one of 1, and NaN otherwise.The test weighs observations with probabilities near 0 or 1 most, so a few confident mistakes can decide it. Like the other calibration tests, it assumes independent outcomes.
References
[1]D. J. Spiegelhalter, “Probabilistic prediction in patient management and clinical trials”, Statistics in Medicine, 5(5), pp. 421-433, 1986.
Examples
Two events among the three lowest probabilities make the probabilities look too confident:
>>> from kivi.calibration import spiegelhalter_test >>> probability = [0.1, 0.2, 0.2, 0.4, 0.7, 0.9] >>> statistic, pvalue = spiegelhalter_test(probability, [0, 1, 1, 0, 0, 1]) >>> print(f"z = {statistic:.3f}, p = {pvalue:.3f}") z = 1.912, p = 0.056
Outcomes that follow the probabilities more closely than chance give a Brier score below its expectation and a negative
z:>>> statistic, pvalue = spiegelhalter_test(probability, [0, 0, 0, 1, 1, 1]) >>> print(f"z = {statistic:.3f}, p = {pvalue:.3f}") z = -0.765, p = 0.444
- kivi.calibration.brier_decomposition(groups, target, probability, *, weights=None)#
Split the Brier score into reliability, resolution, uncertainty and two within-group terms.
The decomposition shows why a model scores as it does. Reliability measures how far the mean probability of each group lies from its event rate, resolution how far the event rates of the groups lie from the overall event rate, and uncertainty how hard the outcomes are to predict at all. The two within-group terms account for the probabilities that vary within a group.
- Parameters:
- groupsarray_like
Grade or group labels, such as the grades of a master scale. Missing values form a group.
- targetarray_like
Binary labels, with 1 indicating the event. A group, or the whole sample, may have no events.
- probabilityarray_like
Predicted event probabilities between 0 and 1. Series inputs must have identical indices; otherwise the inputs are matched by position.
- weightsarray_like, optional
Non-negative frequency weight of each observation, matched like target: integer weights give the same result as repeating rows.
- Returns:
- pandas.Series
brier, the Brier score, and its five termsreliability,resolution,uncertainty,within_varianceandwithin_covariance, in an index namedstatistic.
- Raises:
- ValueError
In the same cases as calibration_table.
See also
calibration_tableThe event rate and mean probability of each group.
kivi.metrics.brier_scoreThe Brier score alone.
spiegelhalter_testTest whether the Brier score is as low as the probabilities predict.
Notes
Let group \(k\) hold \(n_k\) of the \(N\) observations, with mean probability \(\bar f_k\) and event rate \(\bar o_k\), and let \(\bar o\) be the overall event rate. The Brier score of probabilities \(f_i\) and outcomes \(o_i\) is
\[\mathrm{BS} = \frac{1}{N} \sum_i (f_i - o_i)^2 = \mathrm{REL} - \mathrm{RES} + \mathrm{UNC} + \mathrm{WBV} - \mathrm{WBC},\]with
\[ \begin{align}\begin{aligned}\mathrm{REL} = \frac{1}{N} \sum_k n_k (\bar f_k - \bar o_k)^2, \qquad \mathrm{RES} = \frac{1}{N} \sum_k n_k (\bar o_k - \bar o)^2, \qquad \mathrm{UNC} = \bar o (1 - \bar o),\\\mathrm{WBV} = \frac{1}{N} \sum_k \sum_{i \in k} (f_i - \bar f_k)^2, \qquad \mathrm{WBC} = \frac{2}{N} \sum_k \sum_{i \in k} (f_i - \bar f_k)(o_i - \bar o_k).\end{aligned}\end{align} \]The identity holds exactly for any grouping, up to rounding. When all observations of a group have the same probability, as on a master scale whose grades each have one PD, the two within-group terms are 0 and the decomposition is the three-term partition of Murphy [1]; the within-group terms are those of Stephenson, Coelho and Jolliffe [2].
A lower reliability is better and a higher resolution is better. Uncertainty depends on the outcomes alone. With weights, \(n_k\) and \(N\) are sums of weights and every sum weighs its terms.
References
[1]A. H. Murphy, “A new vector partition of the probability score”, Journal of Applied Meteorology, 12(4), pp. 595-600, 1973.
[2]D. B. Stephenson, C. A. S. Coelho and I. T. Jolliffe, “Two extra components in the Brier score decomposition”, Weather and Forecasting, 23(4), pp. 752-757, 2008.
Examples
>>> from kivi.calibration import brier_decomposition >>> grades = ["A", "A", "A", "B", "B", "B"] >>> target = [0, 0, 1, 0, 1, 1] >>> brier_decomposition(grades, target, [0.2, 0.2, 0.2, 0.6, 0.6, 0.6]).round(4) statistic brier 0.2333 reliability 0.0111 resolution 0.0278 uncertainty 0.2500 within_variance 0.0000 within_covariance 0.0000 dtype: float64
Each grade has one probability, so the within-group terms are 0 and 0.0111 - 0.0278 + 0.25 is the Brier score.
- kivi.calibration.herfindahl_index(counts, *, normalize=False)#
Measure how concentrated a portfolio is across grades.
The Herfindahl-Hirschman index is the sum of the squared shares of the grades. It is 1 when every observation is in one grade and \(1/k\) when \(k\) grades are equally full.
- Parameters:
- countsarray_like
Number of observations, or exposure, in each grade, such as the
totalcolumn of calibration_table.- normalizebool, default False
Rescale the index to run from 0 for equally full grades to 1 for a single full grade.
- Returns:
- float
The index.
- Raises:
- ValueError
If counts is not one-dimensional, has negative or non-finite values or sums to zero, or normalize is not a boolean or is set with fewer than two grades.
See also
calibration_tableThe number of observations in each grade.
Notes
For grade shares \(s_i = c_i / \sum_j c_j\) of \(k\) grades,
\[\mathrm{HHI} = \sum_{i=1}^{k} s_i^2, \qquad \mathrm{HHI}^* = \frac{\mathrm{HHI} - 1/k}{1 - 1/k}.\]A rating scale whose observations crowd into a few grades differentiates risk poorly. Empty grades count towards \(k\).
Examples
>>> from kivi.calibration import herfindahl_index >>> herfindahl_index([50, 30, 20]) 0.38 >>> print(f"{herfindahl_index([50, 30, 20], normalize=True):.2f}") 0.07
- kivi.calibration.concentration_test(counts, *, initial_counts=None, initial_cv=None)#
Test whether the grades of a rating scale are more concentrated than at development.
The European Central Bank asks for this test to check that a rating scale still spreads its customers over the grades [1]. It compares the coefficient of variation of the grade shares with its value at the initial validation of the model. A small p-value means that the grades are now more concentrated.
- Parameters:
- countsarray_like
Number of customers, or exposure, in each of the grades of the scale, empty grades included, such as
grades.value_counts(sort=False). At least two grades.- initial_countsarray_like, optional
Number of customers in each grade at the initial validation, for the same grades in the same order. If counts and initial_counts are both Series, they must have identical indices.
- initial_cvfloat, optional
The coefficient of variation at the initial validation, when only that is known. Pass initial_counts or initial_cv, or neither to compute only the HI, as the European Central Bank asks for the exposure-weighted shares.
- Returns:
- pandas.Series
hiandcv, the HI and the coefficient of variation of counts;initial_hiandinitial_cv, those at the initial validation;statistic, the test statistic; andp_value, its one-sided p-value. The last four are NaN without initial_counts and initial_cv. The index is namedstatistic.
- Raises:
- ValueError
If counts or initial_counts is not one-dimensional, has negative or non-finite values or sums to zero, if counts has fewer than two grades or initial_counts another number of grades or another index, if initial_cv is not a finite, non-negative number or exceeds \(\sqrt{K - 1}\), or if both initial_counts and initial_cv are given.
See also
herfindahl_indexThe Herfindahl-Hirschman index of the shares.
calibration_tableThe number of observations in each grade.
Notes
For the shares \(R_i\) of the \(K\) grades, the coefficient of variation and the HI are
\[\mathrm{CV} = \sqrt{K \sum_{i=1}^{K} \left(R_i - \frac{1}{K}\right)^2}, \qquad \mathrm{HI} = 1 + \frac{\ln\left((\mathrm{CV}^2 + 1) / K\right)}{\ln K} = 1 + \frac{\ln \mathrm{HHI}}{\ln K},\]where \(\mathrm{HHI} = \sum_i R_i^2\) is the result of herfindahl_index. The HI is 0 when every grade has the same share and 1 when one grade holds every customer, and the CV runs from 0 to \(\sqrt{K - 1}\). The test statistic
\[S = \frac{\sqrt{K - 1}\,(\mathrm{CV} - \mathrm{CV}_\mathrm{init})} {\sqrt{\mathrm{CV}^2 (0.5 + \mathrm{CV}^2)}}\]is approximately standard normal under the null hypothesis that the current concentration is not above the initial one, which is taken as known, and the p-value is \(1 - \Phi(S)\). The variance in the denominator is the asymptotic variance of a coefficient of variation in Miller [2]. A CV of 0, for equally full grades, gives a statistic of minus infinity and a p-value of 1, or NaN for an initial CV of 0.
References
[1]European Central Bank, “Instructions for reporting the validation results of internal models: IRB Pillar I models for credit risk”, February 2019, section 2.5.5.3.
[2]G. E. Miller, “Asymptotic test statistics for coefficients of variation”, Communications in Statistics - Theory and Methods, 20(10), pp. 3351-3363, 1991.
Examples
>>> from kivi.calibration import concentration_test >>> concentration_test([400, 250, 200, 150], initial_counts=[300, 300, 250, 150]).round(4) statistic hi 0.0945 cv 0.3742 initial_hi 0.0420 initial_cv 0.2449 statistic 0.7477 p_value 0.2273 dtype: float64
The scale is more concentrated than at development, but not significantly so.
- kivi.calibration.backtest_table(groups, realized, estimated, *, weights=None)#
Back-test continuous estimates, such as LGDs or CCFs, against realized values.
For each group, the one-sample t-test for paired observations of the European Central Bank [1] compares the realized values with their estimates. It tests the hypothesis that the estimates are not too low, so a small p-value means that the group’s estimates understate its realized values.
- Parameters:
- groupsarray_like
Grade, pool or segment labels, such as the facility grades of an LGD model or the ECB’s LGD segments cut from the estimates. Missing values form a group. For the whole portfolio, pass one label for every observation.
- realizedarray_like
Realized value of each observation, such as the realized LGD of a closed default. Finite real numbers, which may lie outside [0, 1].
- estimatedarray_like
Estimate of each observation, such as its estimated LGD, ELBE or CCF. Finite real numbers. Series inputs must have identical indices; otherwise the inputs are matched by position.
- weightsarray_like, optional
Non-negative frequency weight of each observation, matched like realized: integer weights give the same result as repeating rows. Groups whose weights sum to zero are left out.
- Returns:
- pandas.DataFrame
One row per group, in an index named
bin, with the number of observationstotal; the meansestimatedandrealized;difference, the mean of realized minus estimated;variance, the sample variance of that difference;statistic, the t statistic; andp_value, its one-sided p-value.
- Raises:
- ValueError
If the inputs are not one-dimensional, are empty, or their indices or lengths do not match, or realized or estimated is not real and numeric or has a missing or infinite value. Also if weights is not numeric, does not give each observation one finite, non-negative weight with a positive total, or has an index other than that of groups.
See also
calibration_tableThe same comparison for event probabilities.
jeffreys_testThe back-test of PDs.
kivi.metrics.generalized_aucThe ranking of continuous estimates.
Notes
For the \(N\) observations of a group with differences \(d_i = r_i - e_i\) between realized and estimated values,
\[T = \frac{\sqrt{N}\,\bar d}{s}, \qquad s^2 = \frac{1}{N - 1} \sum_{i=1}^{N} (d_i - \bar d)^2,\]which follows Student’s t distribution with \(N - 1\) degrees of freedom under the null hypothesis, and the p-value is \(1 - S_{N-1}(T)\). This is the test of sections 2.6.2.1, 2.8.2.1, 2.9.3.1 and 2.9.3.2 of [1] for LGDs, LGDs in default, CCFs and the EAD estimates of facilities with an EAD approach, whose realized value is the amount drawn at default. Section 2.7.2.1 tests the ELBE two-sided; its p-value is
2 * min(p_value, 1 - p_value).A group of one observation has no variance, and its
variance,statisticandp_valueare NaN. A group whose differences are all equal has a variance of 0 and an infinite statistic, or a NaN one when the differences are all 0. With weights, \(N\) is the sum of the weights, the means are weighted, and so is the variance, with the denominator \(N - 1\); a group with a total weight of 1 or less has NaN in the last three columns.Groups are counted as in calibration_table: categorical groups, such as the result of
pandas.cut, follow the order of their categories, with missing values last, and other groups the order in which they first appear.References
Examples
>>> from kivi.calibration import backtest_table >>> grades = ["F1", "F1", "F1", "F2", "F2", "F2", "F2"] >>> realized = [0.05, 0.35, 0.20, 0.55, 0.20, 0.90, 0.75] >>> estimated = [0.15, 0.15, 0.15, 0.45, 0.45, 0.45, 0.45] >>> backtest_table(grades, realized, estimated).round(4) total estimated realized difference variance statistic p_value bin F1 3 0.15 0.2 0.05 0.0225 0.5774 0.3110 F2 4 0.45 0.6 0.15 0.0917 0.9909 0.1974
In grade F1, the differences -0.1, 0.2 and 0.05 have the mean 0.05 and the variance 0.0225, so \(T = \sqrt{3} \cdot 0.05 / 0.15\).
- kivi.calibration.master_scale(probability, *, boundary='geometric', labels=None)#
Build a master scale from the PD of each grade.
A master scale divides the PD range from 0 to 1 into grades, each with one PD. The bounds between adjacent grades lie between their PDs, so that assign_grades can give every predicted PD its grade.
- Parameters:
- probabilityarray_like
PD of each grade, strictly increasing from the grade with the lowest risk and strictly between 0 and 1.
numpy.geomspace(first, last, grades)gives a geometric grid, and fit_grade_pd fits the PDs to observed default rates.- boundary{“geometric”, “arithmetic”}, default “geometric”
Bound between two adjacent grades: the geometric mean of their PDs, the midpoint on a logarithmic scale, or their arithmetic mean.
- labelsarray_like, optional
Unique label of each grade, such as
list("ABCDEFG"). By default the index of probability if it is a Series, such as the result of fit_grade_pd for a table of grades; otherwise the grades are numbered from 1.
- Returns:
- pandas.DataFrame
One row per grade, indexed by its label in an index named
grade, with the columnslower,probabilityandupper. The first grade starts at 0, the last one ends at 1, and each grade ends where the next one starts.
- Raises:
- ValueError
If probability is empty, not one-dimensional or not real and numeric, has a missing value, is not strictly increasing or is not strictly between 0 and 1, boundary is not recognized, or labels (or the index of a Series probability without labels) does not give one unique, non-missing label per grade.
See also
fit_grade_pdFit the PD of each grade to observed default rates.
assign_gradesGive each predicted PD the grade of the scale.
calibration_tableCompare the grades with their observed default rates.
Notes
For the PDs \(p_1 < \dots < p_K\) of the grades, the bound between grades \(k\) and \(k + 1\) is
\[b_k = \sqrt{p_k \, p_{k+1}} \quad \text{(geometric)}, \qquad b_k = \frac{p_k + p_{k+1}}{2} \quad \text{(arithmetic)},\]and grade \(k\) holds the PDs in \((b_{k-1}, b_k]\), with \(b_0 = 0\) and \(b_K = 1\). PDs of a master scale usually grow by a constant factor from grade to grade, so they are evenly spaced on a logarithmic scale. The geometric bound is the midpoint on that scale: a PD goes to the grade whose PD is nearer by ratio. The arithmetic mean, which the 0.2 versions of kivi used, always lies above the geometric one, so each grade reaches further towards the grade above it than towards the grade below. With PDs that double from grade to grade, a grade with PD \(p\) then holds the PDs up to \(1.5 p\) instead of \(\sqrt 2 p \approx 1.41 p\), and its observed default rate tends to exceed its PD.
Examples
>>> import numpy as np >>> from kivi.calibration import master_scale >>> master_scale(np.geomspace(0.01, 0.16, 5), labels=list("ABCDE")).round(4) lower probability upper grade A 0.0000 0.01 0.0141 B 0.0141 0.02 0.0283 C 0.0283 0.04 0.0566 D 0.0566 0.08 0.1131 E 0.1131 0.16 1.0000
The arithmetic mean of adjacent PDs gives higher bounds:
>>> master_scale([0.01, 0.02, 0.04], boundary="arithmetic") lower probability upper grade 1 0.000 0.01 0.015 2 0.015 0.02 0.030 3 0.030 0.04 1.000
A Series gives its index as the labels:
>>> import pandas as pd >>> master_scale(pd.Series([0.01, 0.04], index=["low", "high"])).round(4) lower probability upper grade low 0.00 0.01 0.02 high 0.02 0.04 1.00
- kivi.calibration.fit_grade_pd(event, total, *, smoothing=0.5)#
Fit the PD of each grade to observed default rates, log-linear in the grade.
The logarithm of the default rate is fitted as a straight line in the grade number, so the fitted PDs grow by a constant factor from grade to grade. Pass the result to master_scale for the bounds of the grades.
- Parameters:
- eventarray_like
Number of defaults in each grade, ordered from the grade with the lowest risk to the grade with the highest. Weighted counts, such as those of a weighted calibration_table, must be on the scale of observation counts, because smoothing is a number of defaults: on a smaller scale, such as with weights that sum to 1, the smoothed rate of a grade without defaults is too high.
- totalarray_like
Number of observations in each grade. A grade without observations is left out of the fit but still gets a fitted PD, so pass a 0 for every grade of the scale that the data do not cover. Series inputs must have identical indices.
- smoothingfloat, default 0.5
Number of defaults that replaces a count of zero, whose logarithm is undefined, as kivi.woe.woe_table replaces an empty cell.
- Returns:
- pandas.Series or numpy.ndarray
Fitted PD of each grade, strictly increasing and below 1: a Series with the index of the Series inputs, an array otherwise.
- Raises:
- ValueError
If the inputs are not one-dimensional, have different lengths or Series indices, are not finite and non-negative, or event exceeds total; if fewer than two grades have observations, or smoothing is not finite and positive or not smaller than the total of a grade without defaults. Also if the fitted PDs do not rise with the grade or reach 1.
See also
master_scaleBuild the scale from the fitted PDs.
calibration_tableCount the observations and defaults of each grade.
Notes
With \(d_k\) defaults among \(n_k\) observations in grade \(k = 1, \dots, K\), the intercept \(a\) and the slope \(b\) minimize the weighted sum of squares
\[\sum_{k : n_k > 0} n_k \left(\ln \frac{d_k}{n_k} - a - b k\right)^2,\]where \(d_k\) is replaced by smoothing when it is 0. The fitted PD of grade \(k\) is \(e^{a + b k}\), and consecutive PDs have the constant ratio \(e^b\). The weights give each observation the same influence, so integer counts weigh like repeated observations; the 0.2 versions of kivi fitted the line by ordinary least squares, giving each grade the same influence instead.
The fit extrapolates beyond the observed grades, so grades at the edges of the scale can get PDs no observation supports. A default rate of zero says only that the grade is safe, not how safe: the smoothed rate \(0.5 / n_k\) stands in for it.
Examples
>>> from kivi.calibration import fit_grade_pd >>> event = [0, 3, 5, 18, 30] >>> total = [400, 500, 300, 400, 200] >>> fit_grade_pd(event, total).round(4) array([0.0015, 0.0049, 0.0155, 0.0494, 0.1572])
- kivi.calibration.assign_grades(probability, scale)#
Give each predicted PD the grade of a master scale.
The grades are an ordered categorical of the labels of the scale, so calibration_table counts them directly, in the order of the scale, for the tests of each grade.
- Parameters:
- probabilityarray_like
One-dimensional predicted PDs between 0 and 1. Missing values stay missing.
- scalepandas.DataFrame
Master scale, as returned by master_scale: one row per grade, indexed by unique labels, with the columns
lowerandupper. The first grade must start at 0, each grade where the one before it ends, and the last one must end at 1.
- Returns:
- pandas.Series or pandas.Categorical
Grade of each PD, an ordered categorical whose categories are the labels of the scale from the lowest risk to the highest. A Series input gives a Series with the same index and name.
- Raises:
- ValueError
If probability is not one-dimensional, is not real and numeric, or has values outside [0, 1], or scale is not a DataFrame with unique, non-missing labels and
loweranduppercolumns that cover [0, 1] with increasing, adjacent grades.
See also
master_scaleBuild the scale.
calibration_tableCompare the observed and predicted default rates of each grade.
pandas.cutAssign values to intervals given by their edges.
Notes
Grade \(k\) holds the PDs above its
lowerbound up to and including itsupperbound, as the intervals ofpandas.cutare closed on the right, and a PD of 0 belongs to the first grade, as withinclude_lowest=True. The result equalspandas.cut(probability, edges, labels=scale.index, include_lowest=True)for the edges[0, *scale["upper"]]; theuppercolumn, not the PDs, decides the grade. The 0.2 versions of kivi gave a PD on a bound the grade above it instead.Examples
>>> import pandas as pd >>> from kivi.calibration import assign_grades, master_scale >>> scale = master_scale([0.01, 0.04, 0.16]) >>> scale lower probability upper grade 1 0.00 0.01 0.02 2 0.02 0.04 0.08 3 0.08 0.16 1.00 >>> assign_grades(pd.Series([0.0, 0.02, 0.05, None, 0.9]), scale) 0 1 1 1 2 2 3 NaN 4 3 dtype: category Categories (3, int64): [1 < 2 < 3]
- kivi.calibration.platt_fit(score, target, *, weights=None)#
Fit Platt scaling, a logistic curve from a score to event probabilities.
The slope and intercept are fitted once, on a development or calibration sample, and platt_predict applies them to the scores of any sample.
- Parameters:
- scorearray_like
Finite numeric scores, such as the log odds of a model, a PD or scorecard points. The direction does not matter: a score that falls as the risk rises gets a negative slope.
- targetarray_like
Binary labels, with 1 indicating the event. Both classes must be present. If score and target are both pandas Series, they must have identical indices; otherwise they are matched by position.
- weightsarray_like, optional
Non-negative frequency weight of each observation, matched like target: a weight of 2 counts an observation twice.
- Returns:
- slopefloat
Coefficient of the score in the log odds of the event.
- interceptfloat
Log odds of the event at a score of 0.
- Raises:
- kivi.selection.SeparationError
If the score separates the classes, so that the slope that maximizes the likelihood is infinite. It is a ValueError.
- ValueError
If the inputs are empty or not one-dimensional, their indices or lengths do not match, target has a label other than 0 and 1 or lacks one of them, score is not real and numeric, has a missing or infinite value or does not vary, or weights is invalid or leaves a class without weight.
- Warns:
- RuntimeWarning
If the fit does not converge.
See also
platt_predictApply the slope and intercept to scores.
isotonic_fitA calibration that only assumes that the rate rises.
kivi.selection.logistic_regressionThe same kind of fit with standard errors.
Notes
The event probability at score \(s\) is modelled as
\[p(s) = \frac{1}{1 + \exp(-(a s + b))},\]and the slope \(a\) and the intercept \(b\) maximize the log-likelihood, fitted by iteratively reweighted least squares as in kivi.selection.logistic_regression. At the maximum, the mean fitted probability equals the event rate of the sample, weighted with weights.
When the score is the log odds of a model, this is the logistic recalibration of Cox [2]: a slope of 1 and an intercept of 0 mean that the model is calibrated on the sample, and a slope below 1 that its probabilities are too extreme, as after overfitting.
Platt [1], and scikit-learn’s
CalibratedClassifierCVafter him, replace the labels 1 and 0 with \((n_1 + 1) / (n_1 + 2)\) and \(1 / (n_0 + 2)\) for \(n_1\) events and \(n_0\) non-events. This matters only in small samples, where it also keeps the slope finite when the score separates the classes. Here the labels are used as they are, so a separating score raises an error instead; isotonic_fit handles such a score.References
[1]J. C. Platt, “Probabilistic outputs for support vector machines and comparisons to regularized likelihood methods”, in Advances in Large Margin Classifiers, MIT Press, pp. 61-74, 1999.
[2]D. R. Cox, “Two further applications of a model for binary regression”, Biometrika, 45(3-4), pp. 562-565, 1958.
Examples
>>> from kivi.calibration import platt_fit, platt_predict >>> score = [-2.0, -1.0, -1.0, 0.0, 0.5, 1.0, 1.5, 2.0] >>> target = [0, 0, 1, 0, 1, 0, 1, 1] >>> slope, intercept = platt_fit(score, target) >>> print(f"slope = {slope:.4f}, intercept = {intercept:.4f}") slope = 0.8824, intercept = -0.1250 >>> platt_predict([-1.0, 0.0, 1.0], slope, intercept).round(4) array([0.2675, 0.4688, 0.6808])
- kivi.calibration.platt_predict(score, slope, intercept)#
Turn scores into event probabilities with a fitted Platt scaling.
The probabilities follow the logistic curve with the slope and intercept from platt_fit, so the same calibration applies to the development sample, a validation sample and new applicants.
- Parameters:
- scorearray_like
Numeric scores on the scale of the fit. Missing values give missing probabilities.
- slopefloat
Coefficient of the score, as returned by platt_fit.
- interceptfloat
Intercept, as returned by platt_fit.
- Returns:
- float, pandas.Series or numpy.ndarray
Event probabilities with the shape of score. A Series input gives a Series with the same index and name, and a scalar gives a float.
- Raises:
- ValueError
If score is not real and numeric, or slope or intercept is not a finite number.
See also
platt_fitFit the slope and intercept.
isotonic_predictApply an isotonic calibration.
Notes
The probability is \(1 / (1 + \exp(-(a s + b)))\) for slope \(a\), intercept \(b\) and score \(s\), computed without overflow for extreme scores.
Examples
>>> from kivi.calibration import platt_predict >>> platt_predict([-2.0, 0.0, 2.0], 1.5, -0.5).round(4) array([0.0293, 0.3775, 0.9241])
- kivi.calibration.isotonic_fit(score, target, *, weights=None, increasing=True)#
Fit an isotonic calibration, a step function from a score to event probabilities.
The score range is split into bands whose event rates rise with the score, so the calibration assumes only that a higher score means a higher risk. Fit the bands once and apply them to the scores of any sample with isotonic_predict.
- Parameters:
- scorearray_like
Finite numeric scores, such as a PD or the log odds of a model.
- targetarray_like
Binary labels, with 1 indicating the event. Both classes must be present. If score and target are both pandas Series, they must have identical indices; otherwise they are matched by position.
- weightsarray_like, optional
Non-negative frequency weight of each observation, matched like target: a weight of 2 counts an observation twice. Scores whose weights sum to zero are ignored.
- increasingbool, default True
Whether the probability rises with the score, as for a PD. Pass False for scorecard points, which are higher for a lower risk.
- Returns:
- edgesnumpy.ndarray
Increasing band edges from
-inftoinf, like those of kivi.binning.bin_edges. The bands are closed on the right, as inpandas.cut, and each interior edge is the highest score of the band below it.- probabilitynumpy.ndarray
Event rate of each band, one fewer than edges. The rates are strictly increasing, or strictly decreasing with
increasing=False.
- Raises:
- ValueError
If the inputs are empty or not one-dimensional, their indices or lengths do not match, target has a label other than 0 and 1 or lacks one of them, score is not real and numeric or has a missing or infinite value, weights is invalid or leaves a class without weight, or increasing is not a boolean.
See also
isotonic_predictApply the bands to scores.
platt_fitA calibration by a logistic curve.
calibration_tableCompare the bands with the outcomes of another sample.
Notes
Among all probabilities \(p_i\) that rise with the score, isotonic regression minimizes \(\sum_i w_i (y_i - p_i)^2\), and the same solution maximizes the binomial likelihood [1]. The pool-adjacent-violators algorithm finds it: each distinct score starts as a band with its event rate, and adjacent bands are merged while the lower one has a rate at least as high as the one above it. The probability of a band is then its pooled event rate. Tied scores always share a band, and since bands with equal rates are merged too, no two adjacent bands have the same probability.
The outer edges are infinite, so a score below or above the fitted range gets the probability of the lowest or highest band. A score between the observed scores of two bands falls into the upper one, whose interval it belongs to; with
increasing=False, that is the band with the lower risk. scikit-learn’sIsotonicRegressioninterpolates linearly between the bands instead; both give the same probability at every score of the fitted sample [2].A band without events has probability 0 and a band with only events has probability 1; a score that separates the classes gives just these two bands. Floor the probabilities where 0 is not allowed, for example before kivi.scorecard.pd_to_score. The bands can also serve as the grades of calibration_table, by cutting the scores at edges.
References
[1]M. Ayer, H. D. Brunk, G. M. Ewing, W. T. Reid and E. Silverman, “An empirical distribution function for sampling with incomplete information”, The Annals of Mathematical Statistics, 26(4), pp. 641-647, 1955.
[2]B. Zadrozny and C. Elkan, “Transforming classifier scores into accurate multiclass probability estimates”, Proceedings of the 8th ACM SIGKDD Conference, pp. 694-699, 2002.
Examples
>>> from kivi.calibration import isotonic_fit, isotonic_predict >>> score = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8] >>> target = [0, 1, 0, 0, 1, 0, 1, 1] >>> edges, probability = isotonic_fit(score, target) >>> edges array([-inf, 0.1, 0.4, 0.6, inf]) >>> probability array([0. , 0.33333333, 0.5 , 1. ]) >>> isotonic_predict([0.05, 0.25, 0.45, 0.9], edges, probability).round(4) array([0. , 0.3333, 0.5 , 1. ])
- kivi.calibration.isotonic_predict(score, edges, probability)#
Give each score the probability of its band from an isotonic calibration.
The bands come from isotonic_fit on a development or calibration sample, so the same step function applies to every later sample.
- Parameters:
- scorearray_like
Numeric scores on the scale of the fit. Missing values give missing probabilities.
- edgesarray_like
Increasing band edges from
-inftoinf, as returned by isotonic_fit.- probabilityarray_like
Probability of each band, between 0 and 1, one fewer than edges.
- Returns:
- float, pandas.Series or numpy.ndarray
Event probabilities with the shape of score. A Series input gives a Series with the same index and name, and a scalar gives a float.
- Raises:
- ValueError
If score is not real and numeric, edges is not increasing from
-inftoinf, or probability does not give one value between 0 and 1 for each band.
See also
isotonic_fitFit the bands and their probabilities.
platt_predictApply a Platt scaling.
Notes
The bands are closed on the right, as in
pandas.cut: a score equal to an interior edge gets the probability of the band below the edge. Since the outer edges are infinite, every score that is not missing falls into a band.Examples
>>> from kivi.calibration import isotonic_predict >>> edges = [-float("inf"), 0.2, 0.5, float("inf")] >>> isotonic_predict([0.1, 0.2, 0.3, 0.9], edges, [0.05, 0.2, 0.6]) array([0.05, 0.05, 0.2 , 0.6 ])