Model performance#
Measure how well a score that rises with the event probability separates events from non-events. roc_auc(), gini() and ks() summarize the ranking, roc_table() lists the ROC curve, roc_auc_interval() and delong_test() add DeLong’s standard errors, generalized_auc() extends the AUC with its standard error to ordered outcomes such as realized LGD segments, gains_table() breaks the ranking down by score band, brier_score() compares probabilities with outcomes, and expected_maximum_profit() gives the expected profit of the best cut-off of a credit score.
See Model performance for the definitions, examples and how to read a gains table.
|
Compute the area under the ROC curve of a score. |
|
Compute the Gini coefficient of a score. |
|
Compute the Kolmogorov-Smirnov statistic of a score. |
|
Tabulate the ROC curve of a score, with one row per distinct score. |
|
Estimate the standard error and a confidence interval of the AUC. |
|
Test whether two scores of the same observations have the same AUC. |
|
Measure how well estimated segments rank realized ones, with a standard error. |
|
Summarize events by score band, from the highest scores to the lowest. |
|
Compute the Brier score of predicted event probabilities. |
|
Compute the expected maximum profit of a credit score. |
- kivi.metrics.roc_auc(score, target, *, weights=None)#
Compute the area under the ROC curve of a score.
The AUC is the probability that a randomly chosen event has a higher score than a randomly chosen non-event, with ties counted as one half.
The score comes first and the target second, as in kivi.woe.woe_table; scikit-learn’s metrics take the target first.
- Parameters:
- scorearray_like
Finite numeric scores that are higher for a higher event probability. Negate scorecard points, which are higher for a lower risk.
- 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 weight of each observation, such as the inverse of its sampling rate, matched like target. Every count becomes a sum of weights, so integer weights give the same result as repeating rows.
- Returns:
- float
The AUC, from 0 to 1. A score unrelated to the target gives about 0.5, and a value below 0.5 suggests that the score runs the other way.
- 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, or score 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, has an index other than that of score, or leaves a class without weight.
See also
giniThe same ranking measure on a scale from -1 to 1.
ksLargest gap between the score distributions of the two classes.
gains_tableEvent rates and captured events by score band.
Notes
With \(n_1\) events and \(n_0\) non-events, let \(R_1\) be the sum of the ranks of the events among all scores, where tied scores share their average rank. The Mann-Whitney statistic gives
\[\mathrm{AUC} = \frac{R_1 - n_1 (n_1 + 1) / 2}{n_1 n_0}.\]With weights, each pair of an event \(i\) and a non-event \(j\) counts with weight \(w_i w_j\), and \(n_1\) and \(n_0\) are the total weights of the two classes.
References
[1]J. A. Hanley and B. J. McNeil, “The meaning and use of the area under a receiver operating characteristic (ROC) curve”, Radiology, 143(1), pp. 29-36, 1982.
Examples
>>> from kivi.metrics import roc_auc >>> score = [0.1, 0.4, 0.4, 0.8, 0.7, 0.9] >>> target = [0, 0, 1, 0, 1, 1] >>> round(roc_auc(score, target), 4) 0.7222
Scorecard points are higher for a lower risk, so negate them:
>>> import numpy as np >>> points = np.array([720, 650, 650, 560, 590, 510]) >>> round(roc_auc(-points, target), 4) 0.7222
- kivi.metrics.gini(score, target, *, weights=None)#
Compute the Gini coefficient of a score.
The Gini coefficient rescales the AUC to run from -1 to 1, so that a score unrelated to the target gives about 0.
The score comes first and the target second, as in kivi.woe.woe_table; scikit-learn’s metrics take the target first.
- Parameters:
- scorearray_like
Finite numeric scores that are higher for a higher event probability. Negate scorecard points, which are higher for a lower risk.
- 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 weight of each observation, such as the inverse of its sampling rate, matched like target. Every count becomes a sum of weights, so integer weights give the same result as repeating rows.
- Returns:
- float
The Gini coefficient, from -1 to 1. A negative value suggests that the score runs the other way.
- 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, or score 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, has an index other than that of score, or leaves a class without weight.
See also
Notes
The Gini coefficient, also called the accuracy ratio, is
\[\mathrm{Gini} = 2\,\mathrm{AUC} - 1.\]Examples
>>> from kivi.metrics import gini >>> score = [0.1, 0.4, 0.4, 0.8, 0.7, 0.9] >>> target = [0, 0, 1, 0, 1, 1] >>> round(gini(score, target), 4) 0.4444
- kivi.metrics.ks(score, target, *, weights=None)#
Compute the Kolmogorov-Smirnov statistic of a score.
The KS statistic is the largest gap between the cumulative distribution of the scores of events and that of non-events.
The score comes first and the target second, as in kivi.woe.woe_table; scikit-learn’s metrics take the target first.
- Parameters:
- scorearray_like
Finite numeric scores, such as predicted event probabilities.
- 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 weight of each observation, such as the inverse of its sampling rate, matched like target. Every count becomes a sum of weights, so integer weights give the same result as repeating rows.
- Returns:
- float
The largest gap, from 0 to 1.
- 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, or score 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, has an index other than that of score, or leaves a class without weight.
See also
gains_tableThe gap at the edge of each score band.
roc_aucThe probability that an event scores higher than a non-event.
Notes
Let \(F_1\) and \(F_0\) be the empirical distribution functions of the scores of events and of non-events. Then
\[\mathrm{KS} = \max_t \, \lvert F_1(t) - F_0(t) \rvert,\]where \(t\) runs over the observed scores. With weights, the distribution functions are weighted. As in the two-sample Kolmogorov-Smirnov test, the gap is taken in absolute value, so negated scores give the same KS; use the sign of gini to check the direction.
The largest gap can come from a region where the score runs the wrong way, for example when events gather among the lowest scores as well as the highest. The KS then measures how far apart the two distributions are rather than how well the score ranks events above non-events. The cumulative shares in gains_table show where the gap occurs.
References
[1]L. C. Thomas, D. B. Edelman and J. N. Crook, “Credit Scoring and Its Applications”, SIAM, 2002.
Examples
>>> from kivi.metrics import ks >>> score = [0.1, 0.4, 0.4, 0.8, 0.7, 0.9] >>> target = [0, 0, 1, 0, 1, 1] >>> round(ks(score, target), 4) 0.3333
- kivi.metrics.roc_table(score, target, *, weights=None)#
Tabulate the ROC curve of a score, with one row per distinct score.
Each row flags the observations that score at or above its threshold and counts the events and non-events among them. Plotting
true_positive_rateagainstfalse_positive_rategives the ROC curve, from the highest threshold to the lowest.The score comes first and the target second, as in kivi.woe.woe_table; scikit-learn’s metrics take the target first.
- Parameters:
- scorearray_like
Finite numeric scores that are higher for a higher event probability. Negate scorecard points, which are higher for a lower risk.
- 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 weight of each observation, such as the inverse of its sampling rate, matched like target. The counts become sums of weights, and a score whose observations all have zero weight has no row, so integer weights give the same table as repeating rows.
- Returns:
- pandas.DataFrame
One row per threshold, in an index named
threshold: first infinity, which flags no observation, then every distinct score from the highest to the lowest, which flags them all. The columns are described in the Notes.
- 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, or score 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, has an index other than that of score, or leaves a class without weight.
See also
roc_aucThe area under the curve.
ksThe largest gap between the two rates.
gains_tableThe same cumulative shares by score band.
Notes
The columns are:
cum_non_eventandcum_event: non-events and events that score at or above the threshold, or the sums of their weights;false_positive_rateandtrue_positive_rate: these counts as shares of all non-events and of all events;precision:cum_eventdivided by the sum of both counts, the event rate among the flagged observations, which is NaN in the first row.
Tied scores share a row, so the curve crosses a tie diagonally. The trapezoids under the curve therefore add up to roc_auc, which counts a tied pair as one half,
\[\mathrm{AUC} = \sum_{k \ge 1} (\mathrm{FPR}_k - \mathrm{FPR}_{k-1}) \, \frac{\mathrm{TPR}_k + \mathrm{TPR}_{k-1}}{2},\]and the largest gap between the two rates, \(\max_k \lvert \mathrm{TPR}_k - \mathrm{FPR}_k \rvert\), is ks. The rows are those of
sklearn.metrics.roc_curvewithdrop_intermediate=False.Examples
>>> from kivi.metrics import roc_table >>> score = [0.1, 0.4, 0.4, 0.8, 0.7, 0.9] >>> target = [0, 0, 1, 0, 1, 1] >>> table = roc_table(score, target) >>> table[["cum_non_event", "cum_event", "false_positive_rate", "true_positive_rate"]].round(3) cum_non_event cum_event false_positive_rate true_positive_rate threshold inf 0 0 0.000 0.000 0.9 0 1 0.000 0.333 0.8 1 1 0.333 0.333 0.7 1 2 0.333 0.667 0.4 2 3 0.667 1.000 0.1 3 3 1.000 1.000 >>> table["precision"].round(3).tolist() [nan, 1.0, 0.5, 0.667, 0.6, 0.5]
- kivi.metrics.roc_auc_interval(score, target, *, level=0.95, weights=None)#
Estimate the standard error and a confidence interval of the AUC.
The standard error is that of DeLong, DeLong and Clarke-Pearson [1], which makes no assumption about the distribution of the scores. The interval of the Gini coefficient follows from that of the AUC.
The score comes first and the target second, as in kivi.woe.woe_table; scikit-learn’s metrics take the target first.
- Parameters:
- scorearray_like
Finite numeric scores that are higher for a higher event probability. Negate scorecard points, which are higher for a lower risk.
- targetarray_like
Binary labels, with 1 indicating the event. Without weights there must be at least two events and two non-events. If score and target are both pandas Series, they must have identical indices; otherwise they are matched by position.
- levelfloat, default 0.95
Confidence level of the interval, between 0 and 1.
- weightsarray_like, optional
Non-negative frequency weight of each observation, matched like target. An observation of weight \(w\) counts as \(w\) observations, so integer weights give the same result as repeating rows, standard error included. The weights of each class must add up to more than 1.
- Returns:
- pandas.DataFrame
Two rows,
aucandgini, in an index namedstatistic, and the columnsestimate,sefor the standard error, andlowerandupperfor the bounds of the interval.
- 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, without weights, fewer than two of either, or score is not real and numeric or has a missing or infinite value. Also if level is not a number between 0 and 1, or if weights is not numeric, does not give each observation one finite, non-negative weight, has an index other than that of score, or gives a class a total weight of 1 or less.
See also
roc_aucThe AUC alone.
delong_testCompare the AUCs of two scores on the same observations.
Notes
Let \(n_1\) be the number of events and \(n_0\) that of non-events. The placement value \(V_{10,i}\) of event \(i\) is the share of non-events that score below it, and the placement value \(V_{01,j}\) of non-event \(j\) is the share of events that score above it, with ties counted as one half. Both average to the AUC \(\hat\theta\), and its variance is estimated by
\[\widehat{\mathrm{Var}}(\hat\theta) = \frac{S_{10}}{n_1} + \frac{S_{01}}{n_0}, \qquad S_{10} = \frac{1}{n_1 - 1} \sum_{i=1}^{n_1} (V_{10,i} - \hat\theta)^2,\]with \(S_{01}\) defined in the same way over the non-events. The placement values come from midranks, as in the algorithm of Sun and Xu [2]: the rank of an event among all scores minus its rank among the events is the number of non-events below it, a tie counting as one half. The computation thus takes \(O(N \log N)\) time for \(N\) observations instead of comparing every pair.
The interval is \(\hat\theta \pm z \, \mathrm{SE}\), cut off at 0 and 1, where \(z\) is the quantile of the standard normal distribution at \((1 + \mathrm{level}) / 2\). For the Gini coefficient, \(2\,\mathrm{AUC} - 1\), the estimate and the bounds are rescaled in the same way and the standard error doubles.
The normal approximation is poor when the AUC is close to 0 or 1 or a class has few observations. The standard error is 0 whenever the placement values are constant within each class, as they are for a score that separates the classes perfectly, one that reverses them and a constant score, so the interval collapses to the estimate.
With weights, \(n_1\) and \(n_0\) are the total weights of the two classes, and each squared deviation counts with the weight of its observation. Weights that stand for a population larger than the sample, such as inverse sampling rates, therefore give too small a standard error.
References
[1]E. R. DeLong, D. M. DeLong and D. L. Clarke-Pearson, “Comparing the areas under two or more correlated receiver operating characteristic curves: a nonparametric approach”, Biometrics, 44(3), pp. 837-845, 1988.
[2]X. Sun and W. Xu, “Fast implementation of DeLong’s algorithm for comparing the areas under correlated receiver operating characteristic curves”, IEEE Signal Processing Letters, 21(11), pp. 1389-1393, 2014.
Examples
Six observations leave a wide interval, whose upper bound is cut off at 1:
>>> from kivi.metrics import roc_auc_interval >>> score = [0.1, 0.4, 0.4, 0.8, 0.7, 0.9] >>> target = [0, 0, 1, 0, 1, 1] >>> roc_auc_interval(score, target).round(4) estimate se lower upper statistic auc 0.7222 0.2485 0.2353 1.0 gini 0.4444 0.4969 -0.5295 1.0
- kivi.metrics.delong_test(current, new, target, *, level=0.95, weights=None)#
Test whether two scores of the same observations have the same AUC.
DeLong’s test [1] compares two scores of the same sample, such as a new model and the model it would replace. Both scores rank the same pairs of events and non-events, so their AUCs are correlated, and the standard error of the difference takes that into account.
The scores come first and the target last, as in kivi.strategy.swap_set; scikit-learn’s metrics take the target first.
- Parameters:
- currentarray_like
Finite numeric scores of one model, such as the model in use, that are higher for a higher event probability.
- newarray_like
Finite numeric scores of the other model for the same observations, in the same direction.
- targetarray_like
Binary labels, with 1 indicating the event. Without weights there must be at least two events and two non-events. Any two of current, new and target that are pandas Series must have identical indices; otherwise they are matched by position.
- levelfloat, default 0.95
Confidence level of the interval of the difference, between 0 and 1.
- weightsarray_like, optional
Non-negative frequency weight of each observation, matched like target. An observation of weight \(w\) counts as \(w\) observations, so integer weights give the same result as repeating rows. The weights of each class must add up to more than 1.
- Returns:
- pandas.Series
current_aucandnew_auc, the AUCs of the two scores;difference, which isnew_aucminuscurrent_auc;se, its standard error;lowerandupper, the bounds of its interval at level, cut off at -1 and 1;z, the difference divided by its standard error; andp_value, the two-sided p-value ofz.
- 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, without weights, fewer than two of either, or current or new is not real and numeric or has a missing or infinite value. Also if level is not a number between 0 and 1, or if weights is not numeric, does not give each observation one finite, non-negative weight, has an index other than that of a Series among the scores, or gives a class a total weight of 1 or less.
See also
roc_auc_intervalThe standard error and interval of one AUC.
kivi.strategy.swap_setThe applicants that two scores decide differently at their cut-offs.
Notes
With the placement values of roc_auc_interval computed for each score, let \(D_{10,i}\) be the placement value of event \(i\) under the new score minus that under the current one, and \(D_{01,j}\) the same difference for non-event \(j\). They average to the difference of the AUCs, and its variance is estimated by
\[\widehat{\mathrm{Var}}(\hat\theta_{\mathrm{new}} - \hat\theta_{\mathrm{current}}) = \frac{S^D_{10}}{n_1} + \frac{S^D_{01}}{n_0},\]where \(S^D_{10}\) and \(S^D_{01}\) are the sample variances of \(D_{10,i}\) over the \(n_1\) events and of \(D_{01,j}\) over the \(n_0\) non-events. This equals the variance of the contrast in DeLong et al., which adds the two variances and subtracts twice the covariance. Under the hypothesis of equal AUCs, \(z\) is approximately standard normal.
For a one-sided test that the new score ranks better, halve
p_valuewhenzis positive. When the two scores order every pair of an event and a non-event in the same way, the difference and its standard error are both 0, andzandp_valueare NaN; with fractional weights, a difference and a standard error that are both within rounding error of 0 count as 0. A difference with a standard error of 0, such as that between a constant score and one that separates the classes, gives an infinitezand ap_valueof 0.Weights count as in roc_auc_interval, so inverse sampling rates give too small a standard error.
References
[1]E. R. DeLong, D. M. DeLong and D. L. Clarke-Pearson, “Comparing the areas under two or more correlated receiver operating characteristic curves: a nonparametric approach”, Biometrics, 44(3), pp. 837-845, 1988.
Examples
The new score separates the six observations perfectly:
>>> from kivi.metrics import delong_test >>> current = [0.1, 0.4, 0.4, 0.8, 0.7, 0.9] >>> new = [0.2, 0.3, 0.6, 0.5, 0.7, 0.9] >>> target = [0, 0, 1, 0, 1, 1] >>> delong_test(current, new, target).round(4) current_auc 0.7222 new_auc 1.0000 difference 0.2778 se 0.2485 lower -0.2092 upper 0.7647 z 1.1180 p_value 0.2636 dtype: float64
- kivi.metrics.generalized_auc(estimated, realized, *, level=0.95, weights=None)#
Measure how well estimated segments rank realized ones, with a standard error.
The generalized AUC (gAUC) of the European Central Bank [1] extends the AUC from a binary target to an ordered one, such as the realized LGD of a facility in segments. It is the probability that, of two facilities in different estimated segments, the one estimated higher also realized higher, ties counting as one half. Its rescaled form is Somers’ D.
The estimates come first and the realized values second, as the score and the target do in roc_auc_interval.
- Parameters:
- estimatedarray_like
Estimated segment of each observation, such as the facility grade of an LGD model or its LGD estimate cut into segments: an ordered categorical, such as the result of
pandas.cut, whose order is that of its categories, or numbers, which are ordered by their value. Each distinct value is one row of the contingency table.- realizedarray_like
Realized segment of each observation, such as its realized LGD cut into segments, in the same forms as estimated. If estimated and realized are both Series, they must have identical indices; otherwise they are matched by position.
- levelfloat, default 0.95
Confidence level of the interval, between 0 and 1.
- weightsarray_like, optional
Non-negative frequency weight of each observation, matched like realized: integer weights give the same result as repeating rows, standard error included.
- Returns:
- pandas.DataFrame
Two rows,
gaucandsomers_d, in an index namedstatistic, and the columnsestimate,sefor the standard error, andlowerandupperfor the bounds of the interval.
- Raises:
- ValueError
If the inputs are empty or not one-dimensional, their indices or lengths do not match, have missing values, or are neither real numbers nor ordered categoricals, or if estimated has fewer than two distinct values with a positive weight. Also if level is not a number between 0 and 1, or 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 estimated.
See also
roc_auc_intervalThe AUC of a binary target, with its standard error.
kivi.calibration.backtest_tableBack-test the level of continuous estimates.
Notes
Let \(a_{ij}\) be the number of observations in estimated segment \(i\) and realized segment \(j\), with row totals \(r_i\) and the total \(F\). For each cell, \(A_{ij}\) counts the observations that agree with it in order, \(D_{ij}\) those that disagree:
\[A_{ij} = \sum_{k<i}\sum_{l<j} a_{kl} + \sum_{k>i}\sum_{l>j} a_{kl}, \qquad D_{ij} = \sum_{k>i}\sum_{l<j} a_{kl} + \sum_{k<i}\sum_{l>j} a_{kl}.\]With \(P = \sum_{ij} a_{ij} A_{ij}\), \(Q = \sum_{ij} a_{ij} D_{ij}\) and \(w_r = F^2 - \sum_i r_i^2\), Somers’ D of the realized segments on the estimated ones is
\[D(C|R) = \frac{P - Q}{w_r}, \qquad \mathrm{gAUC} = \frac{D(C|R) + 1}{2},\]and the standard error of the gAUC is
\[s = \frac{1}{w_r^2} \sqrt{\sum_{ij} a_{ij} \left(w_r d_{ij} - (P - Q)(F - r_i)\right)^2}, \qquad d_{ij} = A_{ij} - D_{ij},\]half the asymptotic standard error of Somers’ D of Brown and Benedetti [2], because the gAUC is half of Somers’ D plus one half. The standard error of
somers_dis therefore \(2 s\). The interval is \(\mathrm{gAUC} \pm z s\), cut off at 0 and 1, where \(z\) is the quantile of the standard normal distribution at \((1 + \mathrm{level}) / 2\), and the bounds of Somers’ D follow from it.The normal approximation is poor when the gAUC is close to 0 or 1 or the table holds few observations. The standard error is 0 for a degenerate table, where every realized value falls into one segment or the ranking is perfect or reversed, so the interval collapses to the estimate:
generalized_auc([1, 2, 3, 1], [5, 5, 5, 5])gives a gAUC of 0.5 with a standard error of 0 and the interval [0.5, 0.5].Pairs in the same estimated segment do not count, so a gAUC of 1 means that every pair in different estimated segments is ordered the same way by its realized segments. The AUC leaves out the pairs with the same target instead, so
generalized_auc(target, score), with the binary target in the rows, gives the AUC of a score, though with another standard error than the DeLong standard error of roc_auc_interval. The table has one cell for each pair of distinct values, so cut continuous values into segments first, as the European Central Bank does with twelve LGD segments.With weights, the cells of the table are sums of weights, so the standard error counts the total weight as the number of observations.
References
[1]European Central Bank, “Instructions for reporting the validation results of internal models: IRB Pillar I models for credit risk”, February 2019, sections 2.6.3.1 and 3.2.
[2]M. B. Brown and J. K. Benedetti, “Sampling behavior of tests for correlation in two-way contingency tables”, Journal of the American Statistical Association, 72(358), pp. 309-315, 1977.
Examples
>>> from kivi.metrics import generalized_auc >>> estimated = [1, 1, 1, 2, 2, 2, 3, 3] >>> realized = [1, 1, 2, 1, 2, 3, 2, 3] >>> generalized_auc(estimated, realized).round(4) estimate se lower upper statistic gauc 0.7619 0.0902 0.5852 0.9386 somers_d 0.5238 0.1803 0.1704 0.8772
Of the 21 pairs in different estimated segments, 13 are ordered the same way by the realized segments, 2 the other way and 6 are tied, so Somers’ D is (13 - 2) / 21.
- kivi.metrics.gains_table(score, target, *, bins=10, weights=None)#
Summarize events by score band, from the highest scores to the lowest.
Each row shows how many events a band holds and what share of all events is captured by reviewing that band and every band above it.
The score comes first and the target second, as in kivi.woe.woe_table; scikit-learn’s metrics take the target first.
- Parameters:
- scorearray_like
Finite numeric scores that are higher for a higher event probability. Negate scorecard points, which are higher for a lower risk.
- 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.
- binsint or array_like, default 10
Number of quantile bands, or increasing band edges. An integer is the same as passing
kivi.binning.bin_edges(score, bins=bins), so tied scores can leave fewer bands than requested. Pass the edges fitted on a development sample to compare later samples on the same bands. With weights, an integer gives weighted quantile edges, asbin_edges(score, bins=bins, weights=weights)does.- weightsarray_like, optional
Non-negative weight of each observation, such as the inverse of its sampling rate, matched like target. The counts become sums of weights. On the same edges, integer weights give the same table as repeating rows; an integer bins can give other edges, because weighted quantiles use the inverted CDF.
- Returns:
- pandas.DataFrame
One row per score band, from the highest band to the lowest, indexed by the interval of the band. The columns are described in the Notes.
- 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, bins is neither a positive integer nor increasing edges, or a score lies outside the edges. Also if weights is not numeric, does not give each observation one finite, non-negative weight, has an index other than that of score, or leaves a class without weight.
- Warns:
- UserWarning
If bins is an integer and tied scores leave fewer bands than requested, as in kivi.binning.bin_edges.
See also
ksThe largest gap over all scores rather than band edges.
roc_aucRanking quality over all pairs of events and non-events.
kivi.binning.bin_edgesFit band edges on a development sample.
Notes
Bands are intervals closed on the right, as in
pandas.cut, so tied scores always share a band. Every band is reported, including bands without observations, so samples cut on the same edges give tables with the same rows. An empty band has a NaNevent_rateandlift, andcum_liftis NaN until the first band with observations.The columns are:
non_event,eventandtotal: non-events, events and all observations in the band, or the sums of their weights;event_rate:eventdivided bytotal;lift:event_ratedivided by the event rate of the sample;cum_non_event_share,cum_event_shareandcum_total_share: shares of all non-events, events and observations in the band and the bands above it;ks: the absolute difference betweencum_event_shareandcum_non_event_share;cum_lift:cum_event_sharedivided bycum_total_share.
The largest
ksis at most the value of ks, and the two are equal when each distinct score forms its own band.Examples
>>> from kivi.metrics import gains_table >>> score = [1, 2, 3, 3, 4, 5, 1, 2] >>> target = [0, 0, 1, 0, 1, 1, 0, 0] >>> table = gains_table(score, target, bins=3) >>> table[["total", "event", "event_rate", "cum_event_share", "ks", "lift"]].round(3) total event event_rate cum_event_share ks lift bin (3.0, inf] 2 2 1.0 0.667 0.667 2.667 (2.0, 3.0] 2 1 0.5 1.000 0.800 1.333 (-inf, 2.0] 4 0 0.0 1.000 0.000 0.000
- kivi.metrics.brier_score(probability, target, *, weights=None)#
Compute the Brier score of predicted event probabilities.
The Brier score is the mean squared difference between the predicted probability and the observed outcome, so a lower value is better.
The probabilities come first and the target second, as in kivi.woe.woe_table; scikit-learn’s metrics take the target first.
- Parameters:
- probabilityarray_like
Predicted event probabilities from 0 to 1.
- targetarray_like
Binary labels, with 1 indicating the event. If probability and target are both pandas Series, they must have identical indices; otherwise they are matched by position.
- weightsarray_like, optional
Non-negative weight of each observation, matched like target. The score is then the weighted mean of the squared differences.
- Returns:
- float
The Brier score, from 0 for perfect forecasts to 1.
- 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 or has a missing value or a value outside 0 to 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
roc_aucRanking quality, which ignores the probability scale.
Notes
For outcomes \(y_i\) and probabilities \(p_i\),
\[\mathrm{BS} = \frac{1}{n} \sum_{i=1}^{n} (p_i - y_i)^2,\]or \(\sum_i w_i (p_i - y_i)^2 / \sum_i w_i\) with weights.
Unlike the ranking measures, the Brier score depends on the probability values themselves, so it rewards calibration, and it is defined even when the sample has only one class. Predicting the event rate \(\bar y\) for everyone scores \(\bar y (1 - \bar y)\), a useful baseline.
References
[1]G. W. Brier, “Verification of forecasts expressed in terms of probability”, Monthly Weather Review, 78(1), pp. 1-3, 1950.
Examples
>>> from kivi.metrics import brier_score >>> target = [0, 0, 1, 1] >>> round(brier_score([0.1, 0.3, 0.6, 0.8], target), 4) 0.075
- kivi.metrics.expected_maximum_profit(score, target, *, no_loss_share=0.55, full_loss_share=0.1, roi=0.2644, weights=None)#
Compute the expected maximum profit of a credit score.
The expected maximum profit (EMP) of Verbraken, Bravo, Weber and Baesens [1] is the profit per applicant of the best cut-off of a score, averaged over the uncertain loss of a default. Rejecting a default saves the share of the loan it would lose, and rejecting a good applicant gives up the return on the loan, so the best cut-off depends on that loss.
The score comes first and the target second, as in kivi.woe.woe_table.
- Parameters:
- scorearray_like
Finite numeric scores that are higher for a higher risk, such as a PD. Negate scorecard points, which are higher for a lower risk.
- targetarray_like
Binary labels, with 1 indicating a default. Both classes must be present. If score and target are both pandas Series, they must have identical indices; otherwise they are matched by position.
- no_loss_sharefloat, default 0.55
Probability that a default loses nothing, \(p_0\) in [1]. It must lie between 0 and 1.
- full_loss_sharefloat, default 0.1
Probability that a default loses the whole loan, \(p_1\) in [1]. It must lie between 0 and 1, and together with no_loss_share add up to at most 1. The remaining probability is spread evenly over the losses between 0 and the whole loan.
- roifloat, default 0.2644
Return on investment of a good loan, as a share of the loan amount: the profit given up by rejecting a good applicant. It must be a positive finite number.
- weightsarray_like, optional
Non-negative frequency weight of each observation, such as the inverse of its sampling rate, matched like target. Every count becomes a sum of weights, so integer weights give the same result as repeating rows.
- Returns:
- pandas.Series
Two values in an index named
statistic:emp, the expected maximum profit per applicant as a share of the loan amount, andrejected_share, the share of applicants that the best cut-off rejects, averaged in the same way.
- 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, or score is not real and numeric or has a missing or infinite value. Also if no_loss_share or full_loss_share is not a number between 0 and 1 or they add up to more than 1, roi is not a positive finite number, or weights is not numeric, does not give each observation one finite, non-negative weight, has an index other than that of score, or leaves a class without weight.
See also
kivi.strategy.cutoff_tableRevenue, losses and profit of the approved book at each cut-off.
roc_tableThe ROC curve, whose convex hull holds the best cut-offs.
roc_aucRanking quality, which weighs every cut-off alike.
Notes
Let \(\pi_d\) be the share of defaults and \(\pi_g = 1 - \pi_d\) that of good applicants, and let \(F_d(t)\) and \(F_g(t)\) be the shares of defaults and of good applicants that score above a cut-off \(t\) and are rejected. A default loses the share \(\lambda\) of its loan and a good loan earns the return \(\mathrm{ROI}\), both as shares of the loan amount. Compared with approving everyone, the profit of the cut-off per applicant is
\[P(t; \lambda) = \lambda \, \pi_d F_d(t) - \mathrm{ROI} \, \pi_g F_g(t).\]The loss \(\lambda\) is 0 with probability \(p_0\), 1 with probability \(p_1\), and otherwise uniform between 0 and 1, with the density \(\alpha = 1 - p_0 - p_1\). The EMP averages the profit of the best cut-off for each loss over this distribution \(H\),
\[\mathrm{EMP} = \int_0^1 \max_t P(t; \lambda) \, dH(\lambda),\]and
rejected_shareaverages the share \(\pi_d F_d + \pi_g F_g\) that the best cut-off rejects in the same way.The best cut-off is a vertex of the upper convex hull of the ROC curve, the points \((F_g, F_d)\) of the cut-offs between distinct scores, so tied scores are always rejected together. Let \((F_{g,i}, F_{d,i})\) for \(i = 0, \ldots, m\) be its vertices from (0, 0) to (1, 1). Vertex \(i\) is the best cut-off for the losses from \(\lambda_i\) to \(\lambda_{i+1}\), where \(\lambda_0 = 0\) and
\[\lambda_i = \frac{\mathrm{ROI} \, \pi_g \, (F_{g,i} - F_{g,i-1})} {\pi_d \, (F_{d,i} - F_{d,i-1})},\]which is infinite for a segment without defaults. With \(k\) the last vertex such that \(\lambda_k < 1\), and \(\lambda_{k+1}\) replaced by 1,
\[\mathrm{EMP} = \alpha \sum_{i=0}^{k} \left[ \pi_d F_{d,i} \frac{\lambda_{i+1}^2 - \lambda_i^2}{2} - \mathrm{ROI} \, \pi_g F_{g,i} (\lambda_{i+1} - \lambda_i) \right] + p_1 \left[ \pi_d F_{d,k} - \mathrm{ROI} \, \pi_g F_{g,k} \right],\]and
rejected_sharereplaces each profit by the share rejected at the same vertex, \(\pi_d F_{d,i} + \pi_g F_{g,i}\), integrated over the same losses. A default that loses nothing makes rejecting nobody the best decision, so the mass \(p_0\) adds nothing to either value, and the EMP is never negative. Equation 15 of [1] evaluates the term of \(p_1\) at vertex \(k + 1\); the best cut-off for a full loss is vertex \(k\), as in the R packageEMP[2] and the Python packageempulse[3], whose results this function reproduces.The defaults of no_loss_share, full_loss_share and roi are those of both packages, and the return of 0.2644 is that of the example in [1]. Both packages, like kivi, take 1 as the default and a score that rises with the risk. The EMP depends only on the order of the scores, as the AUC does, but weighs the cut-offs by the profit they earn.
References
[1] (1,2,3,4,5)T. Verbraken, C. Bravo, R. Weber and B. Baesens, “Development and application of consumer credit scoring models using profit-based classification measures”, European Journal of Operational Research, 238(2), pp. 505-513, 2014.
[2]R package
EMP, version 2.0.6, functionempCreditScoring, 2025.[3]Python package
empulse, version 0.14.0, functionempulse.metrics.empcs_score, 2026.Examples
>>> from kivi.metrics import expected_maximum_profit >>> score = [0.1, 0.2, 0.3, 0.4, 0.5, 0.7, 0.8, 0.9] >>> target = [0, 1, 0, 1, 0, 1, 0, 1] >>> expected_maximum_profit(score, target).round(4) statistic emp 0.0975 rejected_share 0.3243 dtype: float64