Binning#

Fit bin edges on a reference sample and group every sample with the same edges. bin_edges() fits quantile or uniform edges from the values alone; chimerge_edges(), tree_edges(), ks_edges() and monotonic_edges() also use a binary target. cut() groups a sample and gives each special code a group of its own.

For categorical variables, category_groups() pools rare categories and chimerge_groups() merges categories with similar event rates; group_categories() applies the resulting dict to a sample.

See Binning for examples and how to choose the edges.

bin_edges(values[, bins, method, special, ...])

Fit numeric bin edges on a reference sample.

cut(values, edges, *[, special])

Assign values to bins, with a separate group for each special value.

chimerge_edges(values, target, *[, ...])

Fit edges by merging adjacent quantile bins with ChiMerge.

tree_edges(values, target, *[, max_bins, ...])

Fit edges with the splits of a decision tree on one variable.

ks_edges(values, target, *[, max_bins, ...])

Fit edges by splitting the values where the classes separate most (Best-KS).

monotonic_edges(values, target, *[, ...])

Fit edges by merging adjacent quantile bins until the WOE is monotonic.

category_groups(values, *[, min_share, ...])

Fit a grouping that pools the rare categories of a reference sample.

chimerge_groups(values, target, *[, ...])

Fit a grouping that merges categories with similar event rates by ChiMerge.

group_categories(values, groups, *[, unseen])

Assign category labels to the groups of a fitted grouping.

kivi.binning.bin_edges(values, bins=5, *, method='quantile', special=None, weights=None)#

Fit numeric bin edges on a reference sample.

The edges are fitted once and then applied with pandas.cut to the reference and to every sample compared with it.

Parameters:
valuesarray_like

One-dimensional numeric reference values, such as a list, a NumPy array or a pandas Series. Missing values are omitted.

binsint, default 5

Requested number of bins. Tied quantiles can reduce this number.

method{“quantile”, “uniform”}, default “quantile”

Use sample quantiles or equally spaced edges.

specialarray_like, optional

Special values, such as codes for “not applicable”, that are omitted when the edges are fitted. Pass the same values to cut so that each one forms its own group.

weightsarray_like, optional

Non-negative weight of each value, for example the inverse of its sampling rate. Values with zero weight are left out. With weights, quantile edges are weighted quantiles by the inverted CDF, so every interior edge is an observed value.

Returns:
numpy.ndarray

Increasing edges with infinite endpoints, suitable for pandas.cut.

Raises:
ValueError

If bins is not a positive integer, method is not recognized, values is not one-dimensional or not numeric, special is not one-dimensional or contains a missing value or a boolean, or the reference has no observations or contains an infinite value apart from special values. Also if weights is not numeric, does not give each value one finite, non-negative weight with a positive total, or has an index other than that of values.

Warns:
UserWarning

If tied edges leave fewer bins than requested, for example when a single value accounts for a large share of the reference.

See also

cut

Assign values to bins, with a separate group for each special value.

pandas.cut

Assign values to the bins defined by the edges.

numpy.quantile

Compute the quantile edges.

kivi.woe.woe_table

Weight of evidence of the resulting groups.

kivi.stability.psi_table

Stability of the resulting groups.

Notes

Quantile edges are the sample quantiles at equally spaced probabilities, computed with the default linear interpolation of numpy.quantile. Uniform edges divide the range from the smallest to the largest value into equal widths.

Repeated edges are merged, and the outer edges are replaced with infinities, so every finite value falls into exactly one interval. The intervals of pandas.cut are closed on the right.

Examples

>>> import pandas as pd
>>> from kivi.binning import bin_edges
>>> values = pd.Series([0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
>>> edges = bin_edges(values, bins=3)
>>> edges
array([-inf,  30.,  60.,  inf])
>>> pd.cut(pd.Series([-5, 45, 200]), edges, labels=False).tolist()
[0, 1, 2]

A special value is left out of the fit:

>>> bin_edges([-1, -1, -1, 10, 20, 30, 40], bins=2, special=[-1])
array([-inf,  25.,  inf])
kivi.binning.cut(values, edges, *, special=None)#

Assign values to bins, with a separate group for each special value.

Without special the result is the same as pandas.cut(values, edges) for every finite value.

Parameters:
valuesarray_like

One-dimensional numeric values to assign. Missing values stay missing. Infinite values must be special codes.

edgesarray_like

Increasing bin edges, usually from bin_edges.

specialarray_like, optional

Special values that each form their own group instead of falling into an interval. Use the values passed to bin_edges.

Returns:
pandas.Series or pandas.Categorical

Categorical groups whose categories are the special values, in the order given, followed by the intervals. A Series input gives a Series with the same index and name.

Raises:
ValueError

If values is not one-dimensional, is not numeric apart from special values or has an infinite value that is not a special value, edges does not increase, or special is not one-dimensional or contains a missing value or a boolean.

See also

bin_edges

Fit the edges on a reference sample.

pandas.cut

Assign values to intervals only.

kivi.woe.woe_table

Weight of evidence of the resulting groups.

kivi.stability.psi_table

Stability of the resulting groups.

Notes

A special value is matched by equality, so -1 and -1.0 are the same code. Values that are not numbers, such as strings read from a file, are also matched after conversion with pandas.to_numeric, so the string "-1" falls into the group of the code -1. Finite values outside the edges become missing, as with pandas.cut; the infinite outer edges of bin_edges avoid this. An infinite value raises an error unless it is a special value, because pandas.cut would leave -inf in no interval, so that it would count as a missing value, and put inf in the last interval.

Examples

>>> import pandas as pd
>>> from kivi.binning import cut
>>> values = pd.Series([-1, 15, 35, None, -1])
>>> cut(values, [-float("inf"), 25, float("inf")], special=[-1])
0          -1
1    (-inf, 25.0]
2     (25.0, inf]
3             NaN
4          -1
dtype: category
Categories (3, object): [-1, (-inf, 25.0], (25.0, inf]]
kivi.binning.chimerge_edges(values, target, *, max_bins=5, alpha=0.05, initial_bins=20, special=None, weights=None)#

Fit edges by merging adjacent quantile bins with ChiMerge.

The values are first cut into initial_bins quantile bins, or into one bin per distinct value if there are no more distinct values than that. The adjacent pair with the smallest chi-square statistic, the pair whose event rates are most alike, is then merged, and merging is repeated while more than max_bins bins remain or while some adjacent pair is not significantly different at level alpha.

Parameters:
valuesarray_like

One-dimensional numeric values, such as a list, a NumPy array or a pandas Series. Missing values and their labels are omitted.

targetarray_like

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

max_binsint, default 5

Maximum number of bins.

alphafloat or None, default 0.05

Significance level of the chi-square test with one degree of freedom. Adjacent bins are merged until every pair differs at this level. Pass None to merge down to max_bins only.

initial_binsint, default 20

Number of quantile bins to start from. Tied quantiles can reduce it.

specialarray_like, optional

Special values, such as codes for “not applicable”, that are omitted with their labels when the edges are fitted. Pass the same values to cut so that each one forms its own group.

weightsarray_like, optional

Non-negative weight of each observation, for example the inverse of its sampling rate, matched like target. Observations with zero weight are left out, and the counts in each bin are sums of weights. The initial quantile bins then use weighted quantiles by the inverted CDF, so unit weights can give other edges than no weights when there are more distinct values than initial_bins. The chi-square test treats the weighted counts as counts, so scale the weights to sum to the sample size when the p-values matter.

Returns:
numpy.ndarray

Increasing edges with infinite endpoints, suitable for pandas.cut.

Raises:
ValueError

If max_bins or initial_bins is not a positive integer, alpha is neither None nor between 0 and 1, values and target are not one-dimensional or their indices or lengths do not match, special is not one-dimensional or contains a missing value or a boolean, values is not numeric or has no finite observations apart from missing and special values, or target has labels other than 0 and 1 or lacks one of them in the rows that are fitted. Also if weights is not numeric, does not give each value one finite, non-negative weight with a positive total, or has an index other than that of values.

See also

tree_edges

Split the values recursively instead of merging.

monotonic_edges

Merge until the WOE is monotonic.

cut

Assign values to bins, with a separate group for each special value.

Notes

For an adjacent pair of bins with observed counts \(O_{ij}\) (bin \(i\), class \(j\)) and expected counts \(E_{ij} = R_i C_j / N\) under equal event rates,

\[\chi^2 = \sum_{i=1}^{2} \sum_{j=0}^{1} \frac{(O_{ij} - E_{ij})^2}{E_{ij}}\]

where cells with \(E_{ij} = 0\) contribute nothing. A pair stays separate when the p-value of \(\chi^2\) is below alpha.

Examples

>>> import pandas as pd
>>> from kivi.binning import chimerge_edges
>>> values = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
>>> target = pd.Series([0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1])
>>> chimerge_edges(values, target)
array([-inf,   4.,  inf])
>>> chimerge_edges(values, target, max_bins=3, alpha=None)
array([-inf,   4.,   9.,  inf])
kivi.binning.tree_edges(values, target, *, max_bins=5, min_bin_share=0.05, criterion='entropy', special=None, weights=None)#

Fit edges with the splits of a decision tree on one variable.

The tree grows best first: of all current bins, the one whose best split most reduces the total impurity is split next, until there are max_bins bins or no split reduces the impurity while leaving at least min_bin_share of the observations on each side.

Parameters:
valuesarray_like

One-dimensional numeric values, such as a list, a NumPy array or a pandas Series. Missing values and their labels are omitted.

targetarray_like

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

max_binsint, default 5

Maximum number of bins, the leaves of the tree.

min_bin_sharefloat, default 0.05

Minimum share of the fitted values in every bin, from 0 to 0.5, or of their total weight when weights is given. Missing and special values do not count towards it.

criterion{“entropy”, “gini”}, default “entropy”

Impurity measure: entropy for information gain, or the Gini index.

specialarray_like, optional

Special values, such as codes for “not applicable”, that are omitted with their labels when the edges are fitted. Pass the same values to cut so that each one forms its own group.

weightsarray_like, optional

Non-negative weight of each observation, for example the inverse of its sampling rate, matched like target. Observations with zero weight are left out, and the counts in each bin are sums of weights.

Returns:
numpy.ndarray

Increasing edges with infinite endpoints, suitable for pandas.cut. Every interior edge is an observed value, the largest one in the bin to its left.

Raises:
ValueError

If max_bins is not a positive integer, min_bin_share is not between 0 and 0.5, criterion is not recognized, values and target are not one-dimensional or their indices or lengths do not match, special is not one-dimensional or contains a missing value or a boolean, values is not numeric or has no finite observations apart from missing and special values, or target has labels other than 0 and 1 or lacks one of them in the rows that are fitted. Also if weights is not numeric, does not give each value one finite, non-negative weight with a positive total, or has an index other than that of values.

See also

chimerge_edges

Merge fine bins instead of splitting.

monotonic_edges

Merge until the WOE is monotonic.

cut

Assign values to bins, with a separate group for each special value.

Notes

For a bin with \(n\) observations (their total weight, with weights) and event rate \(p\), the impurity is \(H(p) = -p \ln p - (1 - p) \ln(1 - p)\) (entropy) or \(G(p) = 2p(1 - p)\) (Gini). A split into \(n_L\) and \(n_R\) observations reduces the total impurity by \(n H(p) - n_L H(p_L) - n_R H(p_R)\), and the largest reduction over all bins and cut points is chosen.

Examples

>>> import pandas as pd
>>> from kivi.binning import tree_edges
>>> values = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
>>> target = pd.Series([0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1])
>>> tree_edges(values, target, max_bins=2)
array([-inf,   4.,  inf])
>>> tree_edges(values, target, max_bins=4)
array([-inf,   4.,   8.,   9.,  inf])
>>> tree_edges(values, target, max_bins=4, min_bin_share=0.1)
array([-inf,   4.,   6.,   9.,  inf])
kivi.binning.ks_edges(values, target, *, max_bins=5, min_bin_share=0.05, special=None, weights=None)#

Fit edges by splitting the values where the classes separate most (Best-KS).

Each split cuts a bin at the value where the cumulative shares of its events and of its non-events differ most, the KS of the bin, among the cuts that leave at least min_bin_share of the observations on each side. The bins are split best first, by the KS of their cut weighted by the shares of the events and the non-events that they hold, until there are max_bins bins or no bin has an allowed cut with a positive KS.

Parameters:
valuesarray_like

One-dimensional numeric values, such as a list, a NumPy array or a pandas Series. Missing values and their labels are omitted.

targetarray_like

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

max_binsint, default 5

Maximum number of bins.

min_bin_sharefloat, default 0.05

Minimum share of the fitted values in every bin, from 0 to 0.5, or of their total weight when weights is given. Missing and special values do not count towards it.

specialarray_like, optional

Special values, such as codes for “not applicable”, that are omitted with their labels when the edges are fitted. Pass the same values to cut so that each one forms its own group.

weightsarray_like, optional

Non-negative weight of each observation, for example the inverse of its sampling rate, matched like target. Observations with zero weight are left out, and the counts in each bin are sums of weights.

Returns:
numpy.ndarray

Increasing edges with infinite endpoints, suitable for pandas.cut. Every interior edge is an observed value, the largest one in the bin to its left.

Raises:
ValueError

If max_bins is not a positive integer, min_bin_share is not between 0 and 0.5, values and target are not one-dimensional or their indices or lengths do not match, special is not one-dimensional or contains a missing value or a boolean, values is not numeric or has no finite observations apart from missing and special values, or target has labels other than 0 and 1 or lacks one of them in the rows that are fitted. Also if weights is not numeric, does not give each value one finite, non-negative weight with a positive total, or has an index other than that of values.

See also

tree_edges

Split where the impurity falls most instead.

chimerge_edges

Merge fine bins instead of splitting.

kivi.metrics.ks

The KS statistic of a score.

cut

Assign values to bins, with a separate group for each special value.

Notes

Let a bin hold \(E_b\) events and \(N_b\) non-events (their total weights, with weights), and let a cut leave \(e\) events and \(n\) non-events on its left. The bin is cut where

\[\mathrm{KS}_b = \left| \frac{e}{E_b} - \frac{n}{N_b} \right|\]

is largest; ties go to the smallest value. With \(E\) events and \(N\) non-events in all the fitted values, the bin split next is the one whose cut has the largest

\[\frac{E_b}{E} \frac{N_b}{N} \mathrm{KS}_b = \frac{\left| e (N_b - n) - (E_b - e) n \right|}{E N}\]

The numerator counts the pairs of an event and a non-event that the cut puts into different bins, the event in the bin with the higher event rate, less the pairs it puts the other way round. The split therefore raises the Gini coefficient of the bins, ranked by event rate, by at least this amount, and by exactly this amount when no other bin has an event rate between those of the two new bins. Ranking the bins by their KS alone would split a bin with a handful of customers as readily as one with thousands, and ranking them by size would spend splits on large bins whose classes barely separate. The first cut is at the KS of the whole sample, among the allowed cuts, and two bins have a Gini coefficient equal to their KS.

Examples

>>> import pandas as pd
>>> from kivi.binning import ks_edges
>>> values = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
>>> target = pd.Series([0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1])
>>> ks_edges(values, target, max_bins=2)
array([-inf,   4.,  inf])
>>> ks_edges(values, target, max_bins=4)
array([-inf,   4.,   8.,   9.,  inf])
>>> ks_edges(values, target, min_bin_share=0.5)
array([-inf,   6.,  inf])
kivi.binning.monotonic_edges(values, target, *, max_bins=5, direction='auto', initial_bins=20, smoothing=0.5, special=None, weights=None)#

Fit edges by merging adjacent quantile bins until the WOE is monotonic.

The values are first cut into initial_bins quantile bins, or into one bin per distinct value if there are no more distinct values than that. While two adjacent bins break the trend, the first such pair is merged and the WOE is recomputed (pool adjacent violators), so the WOE of the final bins is strictly increasing or strictly decreasing. While more than max_bins bins remain, the adjacent pair with the smallest chi-square statistic is merged as in chimerge_edges(), and the trend is checked again.

Parameters:
valuesarray_like

One-dimensional numeric values, such as a list, a NumPy array or a pandas Series. Missing values and their labels are omitted.

targetarray_like

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

max_binsint or None, default 5

Maximum number of bins. Pass None to stop as soon as the WOE is monotonic.

direction{“auto”, “increasing”, “decreasing”}, default “auto”

Trend of the WOE as the values grow. "auto" fits both directions and keeps the one with the larger information value, preferring "increasing" on a tie.

initial_binsint, default 20

Number of quantile bins to start from. Tied quantiles can reduce it.

smoothingfloat, default 0.5

Positive replacement for a zero count when calculating the WOE, as in kivi.woe.woe_table(). Use the same value there to see the same trend.

specialarray_like, optional

Special values, such as codes for “not applicable”, that are omitted with their labels when the edges are fitted. Pass the same values to cut so that each one forms its own group. The trend applies to the intervals only; a special group can have any WOE.

weightsarray_like, optional

Non-negative weight of each observation, for example the inverse of its sampling rate, matched like target. Observations with zero weight are left out, and the counts in each bin are sums of weights. The initial quantile bins then use weighted quantiles by the inverted CDF, so unit weights can give other edges than no weights when there are more distinct values than initial_bins. smoothing is then in units of weight.

Returns:
numpy.ndarray

Increasing edges with infinite endpoints, suitable for pandas.cut.

Raises:
ValueError

If max_bins is neither None nor a positive integer, initial_bins is not a positive integer, direction is not recognized, smoothing is not finite and positive, values and target are not one-dimensional or their indices or lengths do not match, special is not one-dimensional or contains a missing value or a boolean, values is not numeric or has no finite observations apart from missing and special values, or target has labels other than 0 and 1 or lacks one of them in the rows that are fitted. Also if weights is not numeric, does not give each value one finite, non-negative weight with a positive total, or has an index other than that of values.

See also

chimerge_edges

Merge fine bins by a chi-square test.

tree_edges

Split the values recursively.

cut

Assign values to bins, with a separate group for each special value.

Examples

>>> import pandas as pd
>>> from kivi.binning import monotonic_edges
>>> from kivi.woe import woe_table
>>> values = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
>>> target = pd.Series([0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1])
>>> edges = monotonic_edges(values, target)
>>> edges
array([-inf,   4.,   6.,  inf])
>>> woe_table(pd.cut(values, edges), target)["woe"].round(3).tolist()
[-2.159, -0.08, 1.529]
>>> monotonic_edges(values, target, direction="decreasing")
array([-inf,  inf])
kivi.binning.category_groups(values, *, min_share=0.05, min_count=0, rare_label='other', special=None, weights=None)#

Fit a grouping that pools the rare categories of a reference sample.

A category is rare when it makes up less than min_share of the fitted values or has fewer than min_count of them. The rare categories form one group labelled rare_label, and every other category is a group of its own. Apply the grouping with group_categories to the reference and to every sample compared with it.

Parameters:
valuesarray_like

One-dimensional category labels of the reference sample, such as a list, a NumPy array or a pandas Series of strings. Missing values are omitted.

min_sharefloat, default 0.05

Share of the fitted values, from 0 to 1, below which a category is rare. With weights, the share of their total weight.

min_countfloat, default 0

Number of fitted values, or their total weight with weights, below which a category is rare. The default leaves the decision to min_share.

rare_labelstr, int or float, default “other”

Label of the group of rare categories. It must differ from the categories that are not rare and from the special codes.

specialarray_like, optional

Special codes, such as "unknown", that are omitted when the grouping is fitted. Each one is a group of its own, however rare.

weightsarray_like, optional

Non-negative weight of each value, for example the inverse of its sampling rate. Values with zero weight are left out, and the counts of the categories are sums of weights.

Returns:
dict

The group of each category: first the special codes in the order given, then the categories that are not rare, each mapped to itself, then the rare categories, mapped to rare_label. Categories follow the order in which they first appear, or the order of the categories of a categorical input.

Raises:
ValueError

If values is not one-dimensional or has no values apart from missing, special and zero-weight values, min_share is not between 0 and 1, min_count is not a finite, non-negative number, rare_label is neither a string nor a number or is the label of a category that is not rare or of a special code, or special is not one-dimensional or contains a missing value or a boolean. Also if weights is not numeric, does not give each value one finite, non-negative weight with a positive total, or has an index other than that of values.

See also

chimerge_groups

Merge categories with similar event rates.

group_categories

Assign values to the fitted groups.

kivi.woe.woe_table

Weight of evidence of the resulting groups.

kivi.stability.psi_table

Stability of the resulting groups.

Notes

Rare categories are pooled whatever their event rates, so a rare category with a high event rate can share a group with one with a low rate. chimerge_groups uses the target to avoid this. The group of rare categories can itself hold less than min_share of the values.

Examples

>>> import pandas as pd
>>> from kivi.binning import category_groups, group_categories
>>> values = pd.Series(["a", "a", "a", "a", "b", "b", "b", "c", "d", None])
>>> groups = category_groups(values, min_share=0.2)
>>> groups
{'a': 'a', 'b': 'b', 'c': 'other', 'd': 'other'}
>>> group_categories(values, groups).tolist()
['a', 'a', 'a', 'a', 'b', 'b', 'b', 'other', 'other', nan]
kivi.binning.chimerge_groups(values, target, *, max_groups=5, alpha=0.05, min_group_share=0.05, smoothing=0.5, special=None, weights=None)#

Fit a grouping that merges categories with similar event rates by ChiMerge.

The categories are sorted by their WOE, with zero counts smoothed as in kivi.woe.woe_table(), and neighbours in that order are merged. First, while some group holds less than min_group_share of the fitted values, the smallest one is merged with the neighbour whose chi-square statistic with it is smaller. Then, as in chimerge_edges, the adjacent pair with the smallest chi-square statistic is merged while more than max_groups groups remain or while some adjacent pair is not significantly different at level alpha. The groups are sorted by WOE again after every merge, so the WOE of the final groups increases from the first to the last.

Parameters:
valuesarray_like

One-dimensional category labels, such as a list, a NumPy array or a pandas Series of strings. Missing values and their labels are omitted.

targetarray_like

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

max_groupsint, default 5

Maximum number of groups, not counting the special codes.

alphafloat or None, default 0.05

Significance level of the chi-square test with one degree of freedom. Adjacent groups are merged until every pair differs at this level. Pass None to merge down to max_groups only.

min_group_sharefloat, default 0.05

Minimum share of the fitted values in every group, from 0 to 0.5, or of their total weight when weights is given. Missing and special values do not count towards it.

smoothingfloat, default 0.5

Positive replacement for a zero count when calculating the WOE that orders the groups, as in kivi.woe.woe_table(). Use the same value there to see the same order.

specialarray_like, optional

Special codes, such as "unknown", that are omitted with their labels when the grouping is fitted. Each one is a group of its own.

weightsarray_like, optional

Non-negative weight of each observation, for example the inverse of its sampling rate, matched like target. Observations with zero weight are left out, and the counts of each group are sums of weights. The chi-square test treats the weighted counts as counts, so scale the weights to sum to the sample size when the p-values matter. smoothing is then in units of weight.

Returns:
dict

The group of each category: first the special codes in the order given, each mapped to itself, then the categories of each group, in increasing order of the group’s WOE. A group of one category keeps its label; a merged group is labelled with the labels of its categories, in increasing order of their own WOE, joined by ", ". A group of more than five categories shows the first four, followed by ", ... (+n)" with the number n of the others.

Raises:
ValueError

If max_groups is not a positive integer, alpha is neither None nor between 0 and 1, min_group_share is not between 0 and 0.5, smoothing is not finite and positive, values and target are not one-dimensional or their indices or lengths do not match, special is not one-dimensional or contains a missing value or a boolean, values has no values apart from missing, special and zero-weight values, target has labels other than 0 and 1 or lacks one of them in the rows that are fitted, or the label of a merged group would be the label of another group. Also if weights is not numeric, does not give each value one finite, non-negative weight with a positive total, or has an index other than that of values.

See also

category_groups

Pool rare categories without a target.

chimerge_edges

Merge the bins of a numeric variable in the same way.

group_categories

Assign values to the fitted groups.

Notes

The chi-square statistic of two adjacent groups is the one described in chimerge_edges. Sorting by WOE puts categories with similar event rates next to each other, so that each merge joins the categories most alike. A category that is not merged is a group of its own, so with min_group_share=0 and alpha=None a variable with at most max_groups categories keeps all of them.

Ties go to the category that appears first, or that comes first among the categories of a categorical input: categories with the same smoothed WOE keep that order, and of two pairs, or of two small groups, whose statistics or totals agree to a relative 1e-10, the first one is merged. Each merge takes time in proportion to the number of groups, so the fit takes time in proportion to the square of the number of categories, a few seconds for 20,000 of them.

Examples

>>> import pandas as pd
>>> from kivi.binning import chimerge_groups
>>> values = pd.Series(["a"] * 4 + ["b"] * 4 + ["c"] * 4 + ["d"] * 4)
>>> target = pd.Series([0, 0, 0, 1] + [1, 1, 1, 0] + [0, 0, 0, 0] + [1, 1, 1, 1])
>>> chimerge_groups(values, target, max_groups=2, alpha=None)
{'c': 'c, a', 'a': 'c, a', 'b': 'b, d', 'd': 'b, d'}
kivi.binning.group_categories(values, groups, *, unseen='raise')#

Assign category labels to the groups of a fitted grouping.

Each value is replaced with its group in groups, the dict returned by category_groups or chimerge_groups, or one written or edited by hand. Missing values stay missing, so kivi.woe.woe_table() counts them as a group of their own.

Parameters:
valuesarray_like

One-dimensional category labels to assign.

groupsmapping

Group of each category, as a dict from category to group. Neither a category nor a group can be missing.

unseendefault “raise”

Group of the values whose category is not in groups, such as a new category: one of the groups in groups, for example the group of rare categories. By default such values raise an error, so that they never become missing values.

Returns:
pandas.Series or pandas.Categorical

Categorical groups whose categories are the groups in the order in which they first appear in groups. A Series input gives a Series with the same index and name.

Raises:
ValueError

If values is not one-dimensional, groups is not a mapping or has a missing or non-scalar category or group, unseen is neither "raise" nor one of the groups, or unseen is "raise" and some values are categories that groups does not map.

See also

category_groups

Pool rare categories.

chimerge_groups

Merge categories with similar event rates.

cut

Assign numeric values to bins.

kivi.woe.woe_transform

Replace each group with its WOE.

Notes

Categories are matched by equality, as in kivi.woe.woe_transform(), so 1 and 1.0 are the same category but "1" is another. The string "raise" always raises, so it cannot name the group of unseen categories.

Examples

>>> import pandas as pd
>>> from kivi.binning import group_categories
>>> groups = {"a": "a", "b": "b, c", "c": "b, c"}
>>> group_categories(pd.Series(["c", "a", None, "b"]), groups)
0    b, c
1       a
2     NaN
3    b, c
dtype: category
Categories (2, object): ['a', 'b, c']

A category that the grouping does not know raises an error unless unseen names a group for it:

>>> group_categories(["d", "a"], groups)
Traceback (most recent call last):
...
ValueError: values have 1 category that groups does not map, such as 'd'; ...
>>> group_categories(["d", "a"], groups, unseen="b, c")
['b, c', 'a']
Categories (2, object): ['a', 'b, c']