Scorecard#

Turn a logistic regression on WOE values into points. score_scaling(), pd_to_score() and score_to_pd() set and apply the scale, points_table() and woe_to_points() give the points, and reason_codes() lists the variables that lowered a score most.

See Scorecard for a scorecard built on the bundled data.

score_scaling(*, pdo, base_score, base_odds)

Return the factor and offset that turn log odds into a score.

pd_to_score(probability, *, pdo, base_score, ...)

Convert event probabilities to scorecard scores.

score_to_pd(score, *, pdo, base_score, base_odds)

Convert scorecard scores to event probabilities.

points_table(tables, coefficients, ...)

Turn a logistic regression on WOE values into points for each group.

woe_to_points(woe, coefficients, intercept, ...)

Give each applicant the points of each variable from its WOE values.

reason_codes(points, table, *[, top, atol, ...])

Name the variables that cost each applicant the most points.

kivi.scorecard.score_scaling(*, pdo, base_score, base_odds)#

Return the factor and offset that turn log odds into a score.

A scorecard score is linear in the log of the good:bad odds. It equals base_score at odds of base_odds and rises by pdo points each time the odds double.

Parameters:
pdofloat

Points to double the odds. Must be positive.

base_scorefloat

Score at the base odds.

base_oddsfloat

Good:bad odds at the base score, such as 50 for 50 non-events per event. Must be positive.

Returns:
factorfloat

Points per unit of log odds, pdo / ln 2.

offsetfloat

Score at even odds, base_score - factor * ln(base_odds).

Raises:
ValueError

If an argument is not a finite number, or pdo or base_odds is not positive.

See also

pd_to_score

Convert event probabilities to scores.

score_to_pd

Convert scores to event probabilities.

Notes

With odds \(o = (1 - p) / p\) for an event probability \(p\),

\[ \begin{align}\begin{aligned}\mathrm{score} = \mathrm{offset} + \mathrm{factor} \cdot \ln o,\\\mathrm{factor} = \frac{\mathrm{pdo}}{\ln 2}, \qquad \mathrm{offset} = \mathrm{base\_score} - \mathrm{factor} \cdot \ln \mathrm{base\_odds}.\end{aligned}\end{align} \]

Examples

>>> from kivi.scorecard import score_scaling
>>> factor, offset = score_scaling(pdo=20, base_score=600, base_odds=50)
>>> print(f"factor = {factor:.4f}, offset = {offset:.4f}")
factor = 28.8539, offset = 487.1229
kivi.scorecard.pd_to_score(probability, *, pdo, base_score, base_odds)#

Convert event probabilities to scorecard scores.

A lower probability of the event, such as a default, gives a higher score. The scaling is set by pdo, base_score and base_odds, as in score_scaling.

Parameters:
probabilityarray_like

Event probabilities strictly between 0 and 1. Missing values give missing scores.

pdofloat

Points to double the odds. Must be positive.

base_scorefloat

Score at the base odds.

base_oddsfloat

Good:bad odds at the base score. Must be positive.

Returns:
float, pandas.Series or numpy.ndarray

Scores 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 is not real and numeric or has values outside the open interval (0, 1), or the scaling arguments are invalid.

See also

score_to_pd

The inverse conversion.

score_scaling

The factor and offset of the scaling.

Notes

The score is offset + factor * ln((1 - probability) / probability). A probability of exactly 0 or 1 has no finite score and raises an error; see score_to_pd for the scores whose probability rounds to 1.

Examples

>>> from kivi.scorecard import pd_to_score
>>> scale = dict(pdo=20, base_score=600, base_odds=50)
>>> pd_to_score([1 / 51, 1 / 101, 0.1], **scale).round(2)
array([600.  , 620.  , 550.52])
kivi.scorecard.score_to_pd(score, *, pdo, base_score, base_odds)#

Convert scorecard scores to event probabilities.

This is the inverse of pd_to_score for the same scaling, so it gives the probability of the event implied by each score.

Parameters:
scorearray_like

Scores. Missing values give missing probabilities.

pdofloat

Points to double the odds. Must be positive.

base_scorefloat

Score at the base odds.

base_oddsfloat

Good:bad odds at the base score. Must be positive.

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 the scaling arguments are invalid.

See also

pd_to_score

The inverse conversion.

score_scaling

The factor and offset of the scaling.

Notes

The probability is 1 / (1 + exp((score - offset) / factor)), computed without overflow for extreme scores. In double precision it rounds to exactly 1 for scores more than about 36.7 * factor below the offset, -572 for the scale in the example, and pd_to_score rejects such probabilities. Scores that low do not occur on a practical scale.

Examples

>>> from kivi.scorecard import score_to_pd
>>> scale = dict(pdo=20, base_score=600, base_odds=50)
>>> score_to_pd([580, 600, 620], **scale).round(5)
array([0.03846, 0.01961, 0.0099 ])
kivi.scorecard.points_table(tables, coefficients, intercept, *, pdo, base_score, base_odds)#

Turn a logistic regression on WOE values into points for each group.

The points of an applicant’s groups, one per variable, add up to the score that pd_to_score gives for the model’s probability. The intercept is spread evenly across the variables.

Parameters:
tablesmapping

For each variable, its kivi.woe.woe_table result or a Series of WOE values indexed by group. Tables of variables without a coefficient are ignored.

coefficientsmapping or pandas.Series

Logistic regression coefficient of each variable’s WOE, for a model of the event probability. The rows follow this order.

interceptfloat

Intercept of the same model.

pdofloat

Points to double the odds. Must be positive.

base_scorefloat

Score at the base odds.

base_oddsfloat

Good:bad odds at the base score. Must be positive.

Returns:
pandas.DataFrame

One row per variable and group, indexed by variable, with the group label bin and the group’s woe and points. Select a variable’s rows with table.loc[[variable]].

Raises:
ValueError

If tables is not a mapping or lacks a variable of coefficients, a table has no woe column, repeats a group or has non-finite WOE values, the coefficients are empty, repeated or not finite numbers or include the intercept, or the scaling arguments are invalid.

See also

woe_to_points

The points of each applicant.

reason_codes

The variables that cost an applicant the most points.

kivi.woe.woe_table

Fit the WOE of each group.

Notes

With kivi’s WOE, \(\ln(p_i / q_i)\) for event and non-event shares \(p_i\) and \(q_i\), the model is \(\ln \frac{\mathrm{PD}}{1 - \mathrm{PD}} = \beta_0 + \sum_j \beta_j \mathrm{WOE}_j\). A higher WOE means more risk and, for a positive coefficient, fewer points. Group \(i\) of variable \(j\), one of \(m\) variables, receives

\[\mathrm{points}_{ij} = \frac{\mathrm{offset} - \mathrm{factor} \cdot \beta_0}{m} - \mathrm{factor} \cdot \beta_j \, \mathrm{WOE}_{ij},\]

with the factor and offset of score_scaling. Each variable carries the same share of the intercept and offset, so the points of a variable’s groups differ only by their WOE term.

The group labels stay in a column rather than an index level, so labels that compare equal across variables, such as True and 1, keep their own values.

References

[1]

N. Siddiqi, “Credit Risk Scorecards: Developing and Implementing Intelligent Credit Scoring”, Wiley, 2006.

Examples

>>> import pandas as pd
>>> from kivi.scorecard import points_table
>>> tables = {
...     "housing": pd.Series({"no": -0.4, "yes": 0.3}),
...     "contact": pd.Series({"cellular": -0.2, "unknown": 0.6}),
... }
>>> coefficients = {"housing": 0.8, "contact": 0.5}
>>> points_table(tables, coefficients, -2.0, pdo=20, base_score=600, base_odds=50).round(2)
               bin  woe  points
variable
housing         no -0.4  281.65
housing        yes  0.3  265.49
contact   cellular -0.2  275.30
contact    unknown  0.6  263.76
kivi.scorecard.woe_to_points(woe, coefficients, intercept, *, pdo, base_score, base_odds)#

Give each applicant the points of each variable from its WOE values.

The points are those of points_table for the same model and scaling. Their row sums are the scores, equal to pd_to_score of the model’s probabilities.

Parameters:
woepandas.DataFrame or mapping

WOE values with one column per variable, such as the result of kivi.woe.woe_transform for each variable. Columns without a coefficient are ignored. The Series of a mapping must have identical indices; other values are matched by position.

coefficientsmapping or pandas.Series

Logistic regression coefficient of each variable’s WOE, for a model of the event probability. The columns follow this order.

interceptfloat

Intercept of the same model.

pdofloat

Points to double the odds. Must be positive.

base_scorefloat

Score at the base odds.

base_oddsfloat

Good:bad odds at the base score. Must be positive.

Returns:
pandas.DataFrame

Points with the index of woe and one column per variable.

Raises:
ValueError

If woe is not a DataFrame or mapping, lacks or repeats a variable of coefficients, has non-finite values or is a mapping of Series with different indices, the coefficients are empty, repeated, not finite or include the intercept, or the scaling arguments are invalid.

See also

points_table

The points of every group.

reason_codes

The variables that cost an applicant the most points.

Notes

The points of variable \(j\) are \((\mathrm{offset} - \mathrm{factor} \cdot \beta_0) / m - \mathrm{factor} \cdot \beta_j \, \mathrm{WOE}_j\) for \(m\) variables, as in points_table. They are computed in the same way, so rounding both gives the same points.

Examples

>>> import pandas as pd
>>> from kivi.scorecard import woe_to_points
>>> woe = pd.DataFrame({"housing": [-0.4, 0.3], "contact": [0.6, -0.2]})
>>> points = woe_to_points(
...     woe, {"housing": 0.8, "contact": 0.5}, -2.0, pdo=20, base_score=600, base_odds=50
... )
>>> points.round(2)
   housing  contact
0   281.65   263.76
1   265.49   275.30
>>> points.sum(axis=1).round(2).tolist()
[545.41, 540.79]
kivi.scorecard.reason_codes(points, table, *, top=3, atol=0.0001, unseen_points=None)#

Name the variables that cost each applicant the most points.

A variable costs an applicant the difference between the points of the variable’s best group and the points of the applicant’s group. Variables are listed from the largest cost; those that cost nothing are not listed.

Parameters:
pointspandas.DataFrame

Points of each applicant, as returned by woe_to_points.

tablepandas.DataFrame

The points_table result for the same model and scaling.

topint, default 3

Number of reasons per applicant.

atolfloat, default 1e-4

Largest difference, in points, between an applicant’s points and the points of a group for the applicant to be in that group. It absorbs rounding, for example of WOE values stored with six decimals.

unseen_pointsfloat, mapping or pandas.Series, optional

Points of applicants in groups that kivi.woe.woe_transform encoded with unseen, one value for every variable or values by variable. Points that match no group but lie within atol of their variable’s unseen_points cost nothing, so the variable is not a reason for those applicants. They are the woe_to_points result for the WOE passed as unseen; see the Examples. By default every point must match a group.

Returns:
pandas.DataFrame

Variable names in columns reason_1 to reason_<top>, with the index of points. An applicant with fewer costly variables has None in the remaining columns.

Raises:
ValueError

If points is not a DataFrame, repeats a column or has non-finite values, table is not a points_table result, lacks a variable of points or has non-finite points for one, some points are farther than atol from every group of their variable and from its unseen_points, top is not a positive integer, atol is not a finite positive number, or unseen_points is not a finite number or a mapping or Series of finite numbers.

See also

points_table

The points of every group.

woe_to_points

The points of each applicant.

Notes

Each applicant’s points are matched to the nearest group of the variable in table, and the costs are differences between the points of table’s groups. Costs that differ by less than about atol count as equal, so such variables keep the order of the columns of points, and a cost below about atol is no cost.

Points that match no group, such as those from a different intercept or scaling, or WOE values rounded more coarsely than atol allows, raise an error rather than giving reasons against the wrong groups. So do, by default, the points of applicants in a group that had no development observations, such as a new category, whose WOE came from unseen in kivi.woe.woe_transform. That WOE is a value chosen for the group, not evidence about the applicant, so with unseen_points such points give no reason instead of the distance to the best group. Only points near unseen_points are exempt; any other mismatch still raises. Points that lie within atol of a group are matched to that group, even when their WOE came from unseen.

Examples

>>> import pandas as pd
>>> from kivi.scorecard import points_table, reason_codes, woe_to_points
>>> tables = {
...     "housing": pd.Series({"no": -0.4, "yes": 0.3}),
...     "contact": pd.Series({"cellular": -0.2, "unknown": 0.6}),
... }
>>> model = ({"housing": 0.8, "contact": 0.5}, -2.0)
>>> scale = dict(pdo=20, base_score=600, base_odds=50)
>>> table = points_table(tables, *model, **scale)
>>> woe = pd.DataFrame({"housing": [-0.4, 0.3, 0.3], "contact": [-0.2, 0.6, -0.2]})
>>> reason_codes(woe_to_points(woe, *model, **scale), table, top=2)
  reason_1 reason_2
0     None     None
1  housing  contact
2  housing     None

An applicant with a housing status that the development sample did not have was encoded with woe_transform(..., unseen=0.0). The points of a WOE of 0 are the woe_to_points result for a row of zeros, the same base points for every variable. With these points as unseen_points, housing is not one of the applicant’s reasons:

>>> zero = woe_to_points(pd.DataFrame({"housing": [0.0], "contact": [0.0]}), *model, **scale)
>>> zero.round(2)
   housing  contact
0   272.42   272.42
>>> new = pd.DataFrame({"housing": [0.0], "contact": [0.6]})
>>> reason_codes(
...     woe_to_points(new, *model, **scale), table, top=2, unseen_points=zero.iloc[0]
... )
  reason_1 reason_2
0  contact     None