Weight of evidence and information value#

Measure how each group of a variable separates a binary target, and encode groups with the result. woe_table() gives the WOE and IV of each group and woe_transform() encodes new data with them; woe() and iv() compute the same measures from aggregated counts, and woe_trend() names the shape of the WOE over the bins of a numeric variable.

See Weight of evidence and information value for the definitions, examples and how to read the result.

woe_table(groups, target, *[, smoothing, ...])

Compute weight of evidence and information value for observed groups.

woe_transform(groups, table, *[, unseen])

Replace each group with its weight of evidence.

woe(event_counts, non_event_counts, *[, ...])

Compute the weight of evidence of each group from its counts.

iv(event_counts, non_event_counts, *[, ...])

Compute the information value from counts per group.

woe_trend(table)

Name the shape of the WOE over the bins of a numeric variable.

kivi.woe.woe_table(groups, target, *, smoothing=0.5, weights=None)#

Compute weight of evidence and information value for observed groups.

Each group’s share of events is compared with its share of non-events. Sum the iv column for the information value of the variable.

Parameters:
groupsarray_like

Pre-binned values or category labels. Missing values form a group.

targetarray_like

Binary labels, with 1 indicating the event. If groups and target are both pandas Series, they must have identical indices; otherwise they are matched by position.

smoothingfloat, default 0.5

Positive replacement for a zero count when calculating shares.

weightsarray_like, optional

Non-negative weight of each observation, for example the inverse of its sampling rate, matched like target. The counts are then sums of weights, and groups whose weights sum to zero are left out, so woe_transform treats them as unseen. smoothing is then in units of weight: scale the weights to sum to the number of observations, or scale smoothing with them.

Returns:
pandas.DataFrame

One row per group with the columns non_event, event and total (counts), non_event_share and event_share (smoothed shares within each class), total_share (share of all observations), event_rate, woe and iv. Sum the iv column for the variable’s information value.

Raises:
ValueError

If the inputs are not one-dimensional, their indices or lengths do not match, target does not contain both 0 and 1 or has missing or other labels, or smoothing is not finite and positive. Also if weights is not numeric, does not give each observation one finite, non-negative weight, has an index other than that of groups, or leaves a class with a zero total.

See also

woe_transform

Replace each group with its WOE.

woe, iv

The same measures from counts per group.

kivi.binning.bin_edges

Fit edges for numeric variables.

kivi.stability.psi_table

Compare the distribution of two samples.

Notes

For group \(i\), let \(p_i\) and \(q_i\) be its shares of all events and of all non-events. Then

\[\mathrm{WOE}_i = \ln \frac{p_i}{q_i}, \qquad \mathrm{IV}_i = (p_i - q_i)\,\mathrm{WOE}_i, \qquad \mathrm{IV} = \sum_i \mathrm{IV}_i.\]

Each zero count is replaced with smoothing before the shares are normalized, so every WOE is finite. The count columns, total_share and event_rate always use the observed counts.

Categorical groups, such as the result of kivi.binning.cut or pandas.cut, follow the order of their categories with missing values last. Other groups follow the order in which they first appear. Categories that are never observed are omitted.

References

[1]

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

Examples

>>> import pandas as pd
>>> from kivi.woe import woe_table
>>> groups = pd.Series(["a", "a", "a", "b", "b", "b"])
>>> target = pd.Series([1, 1, 0, 1, 0, 0])
>>> woe_table(groups, target)[["event", "non_event", "woe", "iv"]].round(4)
     event  non_event     woe     iv
bin
a        2          1  0.6931  0.231
b        1          2 -0.6931  0.231
kivi.woe.woe_transform(groups, table, *, unseen='raise')#

Replace each group with its weight of evidence.

The WOE values come from a table fitted on the development sample, so a scorecard model sees the same encoding in development, validation and production.

Parameters:
groupsarray_like

One-dimensional group labels formed in the same way as those passed to woe_table, for example with the same edges and pandas.cut.

tablepandas.DataFrame or pandas.Series

The result of woe_table, or a Series of WOE values indexed by group. A missing label in the index gives the WOE of missing values.

unseenfloat or “raise”, default “raise”

Finite WOE for groups that are not in table, such as a new category, an interval without development observations, or missing values when table has no missing group. By default such groups raise an error.

Returns:
pandas.Series or numpy.ndarray

Float WOE values in the order of groups. A Series input gives a Series with the same index and name.

Raises:
ValueError

If groups is not one-dimensional, table has no woe column or repeats a group, unseen is neither "raise" nor a finite number, or unseen is "raise" and some groups are not in table.

See also

woe_table

Fit the WOE of each group.

kivi.binning.bin_edges

Fit the edges used to form numeric groups.

Notes

Labels are matched by equality, so an interval from pandas.cut matches the interval with the same edges in table, and a number matches only an equal label, never the interval that contains it. Use the edges fitted on the development sample for every sample that is transformed.

Examples

>>> import pandas as pd
>>> from kivi.woe import woe_table, woe_transform
>>> groups = pd.Series(["a", "a", "a", "b", "b", "b"])
>>> target = pd.Series([1, 1, 0, 1, 0, 0])
>>> table = woe_table(groups, target)
>>> woe_transform(pd.Series(["b", "a", None]), table, unseen=0.0).round(4).tolist()
[-0.6931, 0.6931, 0.0]
kivi.woe.woe(event_counts, non_event_counts, *, smoothing=0.5)#

Compute the weight of evidence of each group from its counts.

Use this when the counts are already aggregated, for example from a database query or a report, instead of one label per observation.

Parameters:
event_counts, non_event_countsarray_like

One-dimensional, non-negative counts of events and non-events in each group, in the same group order. Two Series must have identical indices. Weighted counts need not be integers.

smoothingfloat, default 0.5

Positive replacement for a zero count when calculating shares.

Returns:
pandas.Series or numpy.ndarray

The WOE of each group. If a count argument is a Series, the result is a Series with its index, named woe; otherwise it is an array.

Raises:
ValueError

If the counts are not one-dimensional, numeric, finite and non-negative, have different lengths or a zero total, or are two Series with different indices, or smoothing is not finite and positive.

See also

iv

The information value of the same counts.

woe_table

Counts, shares, WOE and IV from group labels and a target.

Notes

With \(p_i\) and \(q_i\) the smoothed shares of group \(i\) among all events and all non-events, \(\mathrm{WOE}_i = \ln(p_i / q_i)\), as in the woe column of woe_table.

Examples

>>> import pandas as pd
>>> from kivi.woe import woe
>>> woe([2, 1], [1, 2]).round(4)
array([ 0.6931, -0.6931])
>>> event = pd.Series([2, 1], index=["a", "b"])
>>> non_event = pd.Series([1, 2], index=["a", "b"])
>>> woe(event, non_event).round(4)
a    0.6931
b   -0.6931
Name: woe, dtype: float64
kivi.woe.iv(event_counts, non_event_counts, *, smoothing=0.5)#

Compute the information value from counts per group.

The information value summarizes how well the groups separate events from non-events, from counts that are already aggregated.

Parameters:
event_counts, non_event_countsarray_like

One-dimensional, non-negative counts of events and non-events in each group, in the same group order. Two Series must have identical indices. Weighted counts need not be integers.

smoothingfloat, default 0.5

Positive replacement for a zero count when calculating shares.

Returns:
float

The information value of the variable.

Raises:
ValueError

If the counts are not one-dimensional, numeric, finite and non-negative, have different lengths or a zero total, or are two Series with different indices, or smoothing is not finite and positive.

See also

woe

The weight of evidence of each group.

woe_table

The IV contribution of each group from labels and a target.

kivi.stability.psi

The same divergence between two samples.

Notes

\[\mathrm{IV} = \sum_i (p_i - q_i) \ln \frac{p_i}{q_i},\]

which equals the sum of the iv column of woe_table for the same groups.

Examples

>>> from kivi.woe import iv
>>> round(iv([2, 1], [1, 2]), 4)
0.4621
kivi.woe.woe_trend(table)#

Name the shape of the WOE over the bins of a numeric variable.

The WOE of the rows labeled with an interval is read in the order of the table, which for the bins of kivi.binning.cut or pandas.cut runs from the lowest values of the variable to the highest. Rows of special codes and of missing values have no place on that scale and are left out.

Parameters:
tablepandas.DataFrame or pandas.Series

The result of woe_table, one of the tables of a kivi.spec.BinningSpec, or a Series of WOE values indexed by group, as woe_transform accepts. It needs at least one row labeled with a pandas.Interval.

Returns:
str

One of:

  • 'increasing': the WOE rises from bin to bin;

  • 'decreasing': the WOE falls from bin to bin;

  • 'u_shaped': the WOE falls, then rises;

  • 'inverted_u': the WOE rises, then falls;

  • 'irregular': the direction changes more than once;

  • 'flat': every bin has the same WOE, or there is one bin.

Raises:
ValueError

If table is neither a woe_table result nor a Series, has no woe column or repeats a group, has no row labeled with an interval, as a categorical variable has none, or the WOE of an interval row is not a finite number.

See also

woe_table

The WOE of each group.

kivi.binning.monotonic_edges

Fit edges whose WOE rises or falls from bin to bin.

kivi.plotting.woe_chart

Draw the WOE of each group.

Notes

Two neighbouring bins whose WOE values differ by at most a relative 1e-10 count as equal. Equal neighbours neither rise nor fall, so they do not break a trend: WOE values of 0.1, 0.1 and 0.3 are increasing. A change of direction is a rise followed by a fall, or a fall followed by a rise, across any number of equal neighbours.

The order of the table decides the trend, so a table reordered after woe_table, for example with sort_values("woe"), has the trend of that order. Sort it by its intervals first, as table.sort_index() does when every label is an interval.

Examples

>>> import pandas as pd
>>> from kivi.woe import woe_table, woe_trend
>>> values = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> target = pd.Series([1, 0, 0, 0, 0, 0, 1, 1, 0])
>>> table = woe_table(pd.cut(values, [0, 3, 6, 9]), target)
>>> table["woe"].round(3).tolist()
[-0.154, -1.253, 1.232]
>>> woe_trend(table)
'u_shaped'