Binning tables

Accessing significance tests

After building and analyzing a binning table, use df_tests to retrieve its adjacent-bin significance results without parsing printed output:

table = optb.binning_table
table.build()
table.analysis(print_output=False)
tests = table.df_tests
p_values = tests["p-value"]

This property is available for binary, continuous and multiclass targets. It returns a copy of the results from the most recent successful analysis. Calling it before analysis() raises NotFittedError. With fewer than two regular bins, the result is an empty DataFrame with the usual columns. Special, missing and other-category bins are not compared.

The results are the same tests already reported by analysis(). Binary analysis supports chi-square and Fisher tests and includes Bayesian A/B probabilities; continuous analysis uses Welch’s t-test; multiclass analysis uses the chi-square test. These are bin-comparison results, not p-values for fitted scorecard coefficients.

Binning table: binary target

class optbinning.binning.binning_statistics.BinningTable(name: str, dtype: str, special_codes: dict | list | None, splits: NDArray, n_nonevent: NDArray, n_event: NDArray, weighted: bool, w_n_nonevent: NDArray, w_n_event: NDArray, min_x: float | None = None, max_x: float | None = None, categories: NDArray | list | None = None, cat_others: NDArray | list | None = None, user_splits: NDArray | None = None)

Bases: object

Binning table to summarize optimal binning of a numerical or categorical variable with respect to a binary target.

Parameters:
  • name (str, optional (default="")) – The variable name.

  • dtype (str, optional (default="numerical")) – The variable data type. Supported data types are “numerical” for continuous and ordinal variables and “categorical” for categorical and nominal variables.

  • special_codes (array-like, dict or None, optional (default=None)) – List of special codes. Use special codes to specify the data values that must be treated separately.

  • splits (numpy.ndarray) – List of split points.

  • n_nonevent (numpy.ndarray) – Number of non-events.

  • n_event (numpy.ndarray) – Number of events.

  • weighted (bool) – Whether sample weights were used.

  • w_n_nonevent (numpy.ndarray) – Weighted number of non-events.

  • w_n_event (numpy.ndarray) – Weighted number of events.

  • min_x (float or None (default=None)) – Mininum value of x.

  • max_x (float or None (default=None)) – Maxinum value of x.

  • categories (list, numpy.ndarray or None, optional (default=None)) – List of categories.

  • cat_others (list, numpy.ndarray or None, optional (default=None)) – List of categories in others’ bin.

  • user_splits (numpy.ndarray or None, optional (default=None)) – List of split points pass if prebins were passed by the user.

Warning

This class is not intended to be instantiated by the user. It is preferable to use the class returned by the property binning_table available in all optimal binning classes.

analysis(pvalue_test: str = 'chi2', n_samples: int = 100, print_output: bool = True) → None

Binning table analysis.

Statistical analysis of the binning table, computing the statistics Gini index, Information Value (IV), Jensen-Shannon divergence, and the quality score. Additionally, several statistical significance tests between consecutive bins of the contingency table are performed: a frequentist test using the Chi-square test or the Fisher’s exact test, and a Bayesian A/B test using the beta distribution as a conjugate prior of the Bernoulli distribution.

Parameters:
  • pvalue_test (str, optional (default="chi2")) – The statistical test. Supported test are “chi2” to choose the Chi-square test and “fisher” to choose the Fisher exact test.

  • n_samples (int, optional (default=100)) – The number of samples to run the Bayesian A/B testing between consecutive bins to compute the probability of the event rate of bin A being greater than the event rate of bin B.

  • print_output (bool (default=True)) – Whether to print analysis information.

Notes

The Chi-square test uses scipy.stats.chi2_contingency, and the Fisher exact test uses scipy.stats.fisher_exact.

build(show_digits: int = 2, add_totals: bool = True) → DataFrame

Build the binning table.

Parameters:
  • show_digits (int, optional (default=2)) – The number of significant digits of the bin column.

  • add_totals (bool (default=True)) – Whether to add a last row with totals.

Returns:

binning_table

Return type:

pandas.DataFrame

property df_tests: DataFrame

Statistical significance tests between consecutive bins, computed by analysis().

Returns a table with columns “Bin A”, “Bin B”, “t-statistic” (or “odd ratio” when pvalue_test="fisher"), “p-value”, “P[A > B]” and “P[B > A]” – one row per pair of adjacent regular bins.

Returns:

df_tests – A copy of the results from the most recent successful analysis. Empty when fewer than two regular bins are available. Special, missing and (when present) other-category bins are excluded.

Return type:

pandas.DataFrame

Raises:

NotFittedError – If analysis() has not been called successfully.

property gini

The Gini coefficient or Accuracy Ratio.

The Gini coefficient is a quantitative measure of the discriminatory and predictive power of a variable. The Gini coefficient ranges from 0 to 1.

Returns:

gini

Return type:

float

property hellinger

The Hellinger divergence.

Returns:

hellinger

Return type:

float

property iv

The Information Value (IV) or Jeffrey’s divergence measure.

The IV ranges from 0 to Infinity.

Returns:

iv

Return type:

float

property js

The Jensen-Shannon divergence measure (JS).

The JS ranges from 0 to \(\log(2)\).

Returns:

js

Return type:

float

property ks

The Kolmogorov-Smirnov statistic.

Returns:

ks

Return type:

float

plot(metric: str = 'woe', add_special: bool = True, add_missing: bool = True, style: str = 'bin', show_bin_labels: bool = False, savefig: str | None = None, figsize: tuple | None = None, save_kwargs: dict | None = None, ax: Axes | None = None) → Axes | None

Plot the binning table.

Visualize the non-event and event count, and the Weight of Evidence or the event rate for each bin.

Parameters:
  • metric (str, optional (default="woe")) – Supported metrics are “woe” to show the Weight of Evidence (WoE) measure and “event_rate” to show the event rate.

  • add_special (bool (default=True)) – Whether to add the special codes bin.

  • add_missing (bool (default=True)) – Whether to add the special values bin.

  • style (str, optional (default="bin")) – Plot style. style=”bin” shows the standard binning plot. If style=”actual”, show the plot with the actual scale, i.e, actual bin widths.

  • show_bin_labels (bool (default=False)) –

    Whether to show the bin label instead of the bin id on the x-axis. For long labels (length > 27), labels are truncated.

    Added in version 0.15.1.

  • savefig (str or None (default=None)) – Path to save the plot figure.

  • figsize (tuple or None (default=None)) – Size of the plot.

  • save_kwargs (dict or None (default=None)) – Additional keyword arguments to be passed to plt.savefig.

  • ax (matplotlib.axes.Axes or None (default=None)) – Draw into these axes instead of creating a figure. The caller’s figure is not shown or closed; figsize is ignored in this case.

Returns:

ax – The supplied axes, or None for the existing standalone behavior.

Return type:

matplotlib.axes.Axes or None

property quality_score

The quality score (QS).

The QS is a rating of the quality and discriminatory power of a variable. The QS ranges from 0 to 1.

Returns:

quality_score

Return type:

float

property triangular

The triangular divergence.

Returns:

triangular

Return type:

float

Binning table: continuous target

class optbinning.binning.binning_statistics.ContinuousBinningTable(name: str, dtype: str, special_codes: dict | list | None, splits: NDArray, n_records: NDArray, sums: NDArray, weighted: bool, w_n_records: NDArray, w_sums: NDArray, stds: NDArray, min_target: NDArray, max_target: NDArray, n_zeros: NDArray, min_x: float | None = None, max_x: float | None = None, categories: NDArray | list | None = None, cat_others: NDArray | list | None = None, user_splits: NDArray | None = None)

Bases: object

Binning table to summarize optimal binning of a numerical or categorical variable with respect to a continuous target.

Parameters:
  • name (str, optional (default="")) – The variable name.

  • dtype (str, optional (default="numerical")) – The variable data type. Supported data types are “numerical” for continuous and ordinal variables and “categorical” for categorical and nominal variables.

  • special_codes (array-like, dict or None, optional (default=None)) – List of special codes. Use special codes to specify the data values that must be treated separately.

  • splits (numpy.ndarray) – List of split points.

  • n_records (numpy.ndarray) – Number of records.

  • sums (numpy.ndarray) – Target sums.

  • weighted (bool) – Whether sample weights were used.

  • w_n_records (numpy.ndarray) – Weighted number of records.

  • w_sums (numpy.ndarray) – Weighted target sums.

  • stds (numpy.ndarray) – Target stds.

  • min_target (numpy.ndarray) – Target mininum values.

  • max_target (numpy.ndarray) – Target maxinum values.

  • n_zeros (numpy.ndarray) – Number of zeros.

  • min_x (float or None (default=None)) – Mininum value of x.

  • max_x (float or None (default=None)) – Maxinum value of x.

  • categories (list, numpy.ndarray or None, optional (default=None)) – List of categories.

  • cat_others (list, numpy.ndarray or None, optional (default=None)) – List of categories in others’ bin.

  • user_splits (numpy.ndarray or None, optional (default=None)) – List of split points pass if prebins were passed by the user.

Warning

This class is not intended to be instantiated by the user. It is preferable to use the class returned by the property binning_table available in all optimal binning classes.

analysis(print_output: bool = True) → None

Binning table analysis.

Statistical analysis of the binning table, computing the Information Value (IV) and Herfindahl-Hirschman Index (HHI).

Parameters:

print_output (bool (default=True)) – Whether to print analysis information.

Notes

The IV for a continuous target is computed as follows:

\[IV = \sum_{i=1}^n |U_i - \mu| \frac{r_i}{r_T},\]

where \(U_i\) is the target mean value for each bin, \(\mu\) is the total target mean, \(r_i\) is the number of records for each bin, and \(r_T\) is the total number of records.

build(show_digits: int = 2, add_totals: bool = True) → DataFrame

Build the binning table.

Parameters:
  • show_digits (int, optional (default=2)) – The number of significant digits of the bin column.

  • add_totals (bool (default=True)) – Whether to add a last row with totals.

Returns:

binning_table

Return type:

pandas.DataFrame

property df_tests: DataFrame

Statistical significance tests between consecutive bins, computed by analysis().

Returns a table with columns “Bin A”, “Bin B”, “t-statistic” and “p-value” – one row per pair of adjacent regular bins.

Returns:

df_tests – A copy of the results from the most recent successful analysis. Empty when fewer than two regular bins are available. Special, missing and (when present) other-category bins are excluded.

Return type:

pandas.DataFrame

Raises:

NotFittedError – If analysis() has not been called successfully.

property iv

The Information Value (IV).

The IV ranges from 0 to Infinity.

Returns:

iv

Return type:

float

plot(add_special: bool = True, add_missing: bool = True, style: str = 'bin', show_bin_labels: bool = False, savefig: str | None = None, figsize: tuple | None = None, metric: str = 'mean', ax: Axes | None = None) → Axes | None

Plot the binning table.

Visualize records count and mean values.

Parameters:
  • metric (str, optional (default="mean")) –

    Supported metrics are “mean” to show the Mean value of the target variable in each bin, “iv” to show the IV of each bin and “woe” to show the Weight of Evidence (WoE) of each bin.

    Added in version 0.19.0.

  • add_special (bool (default=True)) – Whether to add the special codes bin.

  • add_missing (bool (default=True)) – Whether to add the special values bin.

  • style (str, optional (default="bin")) – Plot style. style=”bin” shows the standard binning plot. If style=”actual”, show the plot with the actual scale, i.e, actual bin widths.

  • show_bin_labels (bool (default=False)) –

    Whether to show the bin label instead of the bin id on the x-axis. For long labels (length > 27), labels are truncated.

    Added in version 0.15.1.

  • savefig (str or None (default=None)) – Path to save the plot figure.

  • figsize (tuple or None (default=None)) – Size of the plot.

  • ax (matplotlib.axes.Axes or None (default=None)) – Draw into these axes instead of creating a figure. The caller’s figure is not shown or closed; figsize is ignored in this case.

Returns:

ax – The supplied axes, or None for the existing standalone behavior.

Return type:

matplotlib.axes.Axes or None

property quality_score

The quality score (QS).

The QS is a rating of the quality and discriminatory power of a variable. The QS ranges from 0 to 1.

Returns:

quality_score

Return type:

float

property woe

The sum of absolute WoEs.

This metric is computed as follows:

\[WoE = \sum_{i=1}^n |U_i - \mu|,\]

where \(U_i\) is the target mean value for each bin, \(\mu\) is the total target mean.

Returns:

woe

Return type:

float

Binning table: multiclass target

class optbinning.binning.binning_statistics.MulticlassBinningTable(name: str, special_codes: dict | list | None, splits: NDArray, n_event: NDArray, classes: list)

Bases: object

Binning table to summarize optimal binning of a numerical variable with respect to a multiclass or multilabel target.

Parameters:
  • name (str, optional (default="")) – The variable name.

  • splits (numpy.ndarray) – List of split points.

  • n_event (numpy.ndarray) – Number of events.

  • classes (array-like) – List of classes.

Warning

This class is not intended to be instantiated by the user. It is preferable to use the class returned by the property binning_table available in all optimal binning classes.

analysis(print_output: bool = True) → None

Binning table analysis.

Statistical analysis of the binning table, computing the Jensen-shannon divergence and the quality score. Additionally, a statistical significance test between consecutive bins of the contingency table is performed using the Chi-square test.

Parameters:

print_output (bool (default=True)) – Whether to print analysis information.

Notes

The Chi-square test uses scipy.stats.chi2_contingency.

build(show_digits: int = 2, add_totals: bool = True) → DataFrame

Build the binning table.

Parameters:
  • show_digits (int, optional (default=2)) – The number of significant digits of the bin column.

  • add_totals (bool (default=True)) – Whether to add a last row with totals.

Returns:

binning_table

Return type:

pandas.DataFrame

property df_tests: DataFrame

Statistical significance tests between consecutive bins, computed by analysis().

Returns a table with columns “Bin A”, “Bin B”, “t-statistic” and “p-value” – one row per pair of adjacent regular bins.

Returns:

df_tests – A copy of the results from the most recent successful analysis. Empty when fewer than two regular bins are available. Special, missing and (when present) other-category bins are excluded.

Return type:

pandas.DataFrame

Raises:

NotFittedError – If analysis() has not been called successfully.

property js

The Jensen-Shannon divergence measure (JS).

The JS ranges from 0 to \(\log(n_{classes})\).

Returns:

js

Return type:

float

plot(add_special: bool = True, add_missing: bool = True, show_bin_labels: bool = False, savefig: str | None = None, figsize: tuple | None = None, ax: Axes | None = None) → Axes | None

Plot the binning table.

Visualize event count and event rate values for each class.

Parameters:
  • add_special (bool (default=True)) – Whether to add the special codes bin.

  • add_missing (bool (default=True)) – Whether to add the special values bin.

  • show_bin_labels (bool (default=False)) –

    Whether to show the bin label instead of the bin id on the x-axis. For long labels (length > 27), labels are truncated.

    Added in version 0.15.1.

  • savefig (str or None (default=None)) – Path to save the plot figure.

  • figsize (tuple or None (default=None)) – Size of the plot.

  • ax (matplotlib.axes.Axes or None (default=None)) – Draw into these axes instead of creating a figure. The caller’s figure is not shown or closed; figsize is ignored in this case.

Returns:

ax – The supplied axes, or None for the existing standalone behavior.

Return type:

matplotlib.axes.Axes or None

property quality_score

The quality score (QS).

The QS is a rating of the quality and discriminatory power of a variable. The QS ranges from 0 to 1.

Returns:

quality_score

Return type:

float