Binning process
- class optbinning.BinningProcess(variable_names: ArrayLike | list[str] | None = None, max_n_prebins: int = 20, min_prebin_size: float = 0.05, min_n_bins: int | None = None, max_n_bins: int | None = None, min_bin_size: float | None = None, max_bin_size: float | None = None, max_pvalue: float | None = None, max_pvalue_policy: str = 'consecutive', selection_criteria: dict[str, Any] | None = None, fixed_variables: ArrayLike | list[str] | None = None, categorical_variables: ArrayLike | list[str] | None = None, special_codes: ArrayLike | None = None, split_digits: int | None = None, binning_fit_params: dict[str, Any] | None = None, binning_transform_params: dict[str, Any] | None = None, n_jobs: int | None = None, verbose: bool = False, target_dtype: str | None = None)
Bases:
Base,TransformerMixin,BaseEstimator,BaseBinningProcessBinning process to compute optimal binning of variables in a dataset, given a binary, continuous or multiclass target dtype.
- Parameters:
variable_names (array-like or None, optional (default=None)) –
List of variable names. If None, names are inferred from
Xat fit time: column names for apandas.DataFrame, or"x0", "x1", ...for anumpy.ndarray. Required (cannot be None) when usingfit_disk.Changed in version 1.1.0:
variable_namesis now optional.max_n_prebins (int (default=20)) – The maximum number of bins after pre-binning (prebins).
min_prebin_size (float (default=0.05)) – The fraction of minimum number of records for each prebin (including missing and
special_codegroups). Counted in records, regardless ofsample_weight.min_n_bins (int or None, optional (default=None)) – The minimum number of bins. If None, then
min_n_binsis a value in[0, max_n_prebins].max_n_bins (int or None, optional (default=None)) – The maximum number of bins. If None, then
max_n_binsis a value in[0, max_n_prebins].min_bin_size (float or None, optional (default=None)) – The fraction of minimum number of records for each bin (including missing and
special_codegroups). If None,min_bin_size = min_prebin_size. Counted in records, regardless ofsample_weight.max_bin_size (float or None, optional (default=None)) – The fraction of maximum number of records for each bin (including missing and
special_codegroups). If None,max_bin_size = 1.0. Counted in records, regardless ofsample_weight.max_pvalue (float or None, optional (default=None)) – The maximum p-value among bins.
max_pvalue_policy (str, optional (default="consecutive")) – The method to determine bins not satisfying the p-value constraint. Supported methods are “consecutive” to compare consecutive bins and “all” to compare all bins.
selection_criteria (dict or None (default=None)) –
Variable selection criteria. See notes.
Added in version 0.6.0.
fixed_variables (array-like or None) –
List of variables to be fixed. The binning process will retain these variables if the selection criteria is not satisfied.
Added in version 0.12.1.
categorical_variables (array-like or None, optional (default=None)) – List of variables numerical variables to be considered categorical. These are nominal variables. Not applicable when target type is multiclass.
special_codes (array-like or None, optional (default=None)) – List of special codes. Use special codes to specify the data values that must be treated separately.
split_digits (int or None, optional (default=None)) – The significant digits of the split points. If
split_digitsis set to 0, the split points are integers. Negative values round to the left of the decimal point (e.g., -2 rounds to the nearest 100). If None, then all significant digits in the split points are considered.binning_fit_params (dict or None, optional (default=None)) – Dictionary with optimal binning fitting options for specific variables. Example:
{"variable_1": {"max_n_bins": 4}}.binning_transform_params (dict or None, optional (default=None)) – Dictionary with optimal binning transform options for specific variables. Example
{"variable_1": {"metric": "event_rate"}}.target_dtype (str or None, optional (default=None)) –
The target type, one of “binary”, “continuous” or “multiclass”. If None, inferred automatically via
sklearn.utils.multiclass.type_of_target. Set explicitly to override auto-detection, e.g. for an integer-valued continuous target (see GH issue #296).Added in version 1.1.0.
n_jobs (int or None, optional (default=None)) –
Number of cores to run in parallel while binning variables.
Nonemeans 1 core.-1means using all processors.Added in version 0.7.1.
verbose (bool (default=False)) – Enable verbose output.
Notes
Parameter
selection_criteriaallows to specify criteria for variable selection. The input is a dictionary as followsselection_criteria = { "metric_1": { "min": 0, "max": 1, "strategy": "highest", "top": 0.25 }, "metric_2": { "min": 0.02 } }
where several metrics can be combined. For example, above dictionary indicates that top 25% variables with “metric_1” in [0, 1] and “metric_2” greater or equal than 0.02 are selected. Supported key values are:
keys
minandmaxsupport numerical values.key
strategysupports options “highest” and “lowest”.key
topsupports an integer or decimal (percentage).
Warning
If the binning process instance is going to be saved, do not pass the option
"solver": "mip"via thebinning_fit_paramsparameter.- fit(X: NDArray | DataFrame, y: ArrayLike, sample_weight: ArrayLike | None = None, check_input: bool = False) Self
Fit the binning process. Fit the optimal binning to all variables according to the given training data.
- Parameters:
X (numpy.ndarray or pandas.DataFrame of shape (n_samples, n_features)) –
Training vector, where n_samples is the number of samples.
Changed in version 0.4.0.
X supports
numpy.ndarrayandpandas.DataFrame.y (array-like of shape (n_samples,)) – Target vector relative to x.
sample_weight (array-like of shape (n_samples,) (default=None)) – Array of weights that are assigned to individual samples. If not provided, then each sample is given unit weight. Weights are used for the weighted bin counts and statistics (WoE, IV, event rate or mean, p-value), for any
prebinning_method. Withprebinning_method="cart", they are also used to fit the decision tree. This option is only available for binary and continuous targets.check_input (bool (default=False)) – Whether to check input arrays.
- Returns:
self – Fitted binning process.
- Return type:
- fit_disk(input_path: str, target: str, **kwargs) Self
Fit the binning process according to the given training data on disk.
- Parameters:
input_path (str) – Any valid string path to a file with extension .csv or .parquet.
target (str) – Target column.
**kwargs (keyword arguments) – Keyword arguments for
pandas.read_csvorpandas.read_parquet.
- Returns:
self – Fitted binning process.
- Return type:
- fit_from_dict(dict_optb: dict[str, object]) Self
Fit the binning process from a dict of OptimalBinning objects already fitted.
- Parameters:
dict_optb (dict) – Dictionary with OptimalBinning objects for binary, continuous or multiclass target. All objects must share the same class.
- Returns:
self – Fitted binning process.
- Return type:
- fit_transform(X: NDArray | DataFrame, y: ArrayLike, sample_weight: ArrayLike | None = None, metric: str | None = None, metric_special: float | str = 0, metric_missing: float | str = 0, show_digits: int = 2, check_input: bool = False) ndarray
Fit the binning process according to the given training data, then transform it.
- Parameters:
X (numpy.ndarray or pandas.DataFrame of shape (n_samples, n_features)) – Training vector, where n_samples is the number of samples.
y (array-like of shape (n_samples,)) – Target vector relative to x.
sample_weight (array-like of shape (n_samples,) (default=None)) – Array of weights that are assigned to individual samples. If not provided, then each sample is given unit weight. Weights are used for the weighted bin counts and statistics (WoE, IV, event rate or mean, p-value), for any
prebinning_method. Withprebinning_method="cart", they are also used to fit the decision tree. This option is only available for binary and continuous targets.metric (str or None, (default=None)) – The metric used to transform the input vector. If None, the default transformation metric for each target type is applied. For binary target options are: “woe” (default), “event_rate”, “indices” and “bins”. For continuous target options are: “mean” (default), “indices” and “bins”. For multiclass target options are: “mean_woe” (default), “weighted_mean_woe”, “indices” and “bins”.
metric_special (float or str (default=0)) – The metric value to transform special codes in the input vector. Supported metrics are “empirical” to use the empirical WoE or event rate for a binary target, and any numerical value for other targets.
metric_missing (float or str (default=0)) – The metric value to transform missing values in the input vector. Supported metrics are “empirical” to use the empirical WoE or event rate for a binary target, and any numerical value for other targets.
show_digits (int, optional (default=2)) – The number of significant digits of the bin column. Applies when
metric="bins".check_input (bool (default=False)) – Whether to check input arrays.
- Returns:
X_new – Transformed array.
- Return type:
numpy array, shape = (n_samples, n_features_new)
- fit_transform_disk(input_path: str, output_path: str, target: str, chunksize: int, metric: str | None = None, metric_special: float | str = 0, metric_missing: float | str = 0, show_digits: int = 2, **kwargs) Self
Fit the binning process according to the given training data on disk, then transform it and save to comma-separated values (csv) file.
- Parameters:
input_path (str) – Any valid string path to a file with extension .csv.
output_path (str) – Any valid string path to a file with extension .csv.
target (str) – Target column.
chunksize (int) – Rows to read, transform and write at a time.
metric (str or None, (default=None)) – The metric used to transform the input vector. If None, the default transformation metric for each target type is applied. For binary target options are: “woe” (default), “event_rate”, “indices” and “bins”. For continuous target options are: “mean” (default), “indices” and “bins”. For multiclass target options are: “mean_woe” (default), “weighted_mean_woe”, “indices” and “bins”.
metric_special (float or str (default=0)) – The metric value to transform special codes in the input vector. Supported metrics are “empirical” to use the empirical WoE or event rate for a binary target, and any numerical value for other targets.
metric_missing (float or str (default=0)) – The metric value to transform missing values in the input vector. Supported metrics are “empirical” to use the empirical WoE or event rate for a binary target, and any numerical value for other targets.
show_digits (int, optional (default=2)) – The number of significant digits of the bin column. Applies when
metric="bins".**kwargs (keyword arguments) – Keyword arguments for
pandas.read_csv.
- Returns:
self – Fitted binning process.
- Return type:
- get_binned_variable(name: str) BaseOptimalBinning
Return optimal binning object for a given variable name.
- Parameters:
name (str) – The variable name.
- Returns:
optb – Optimal binning class (binary or continuous).
- Return type:
BaseOptimalBinning
- get_feature_names_out(input_features=None)
Get output feature names for transformation.
- Parameters:
input_features (array-like of str or None, optional (default=None)) – Not used, present for API consistency by convention.
- Returns:
feature_names_out – Transformed feature names, i.e., the names of the selected variables.
- Return type:
ndarray of str
- get_metadata_routing()
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
- Returns:
routing – A
MetadataRequestencapsulating routing information.- Return type:
MetadataRequest
- get_params(deep=True)
Get parameters for this estimator.
- Parameters:
deep (bool, default=True) – If True, will return the parameters for this estimator and contained subobjects that are estimators.
- Returns:
params – Parameter names mapped to their values.
- Return type:
dict
- get_support(indices: bool = False, names: bool = False) ndarray
Get a mask, or integer index, or names of the variables selected.
- Parameters:
indices (boolean (default=False)) – If True, the return value will be an array of integers, rather than a boolean mask.
names (boolean (default=False)) – If True, the return value will be an array of strings, rather than a boolean mask.
- Returns:
support – An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector. If names is True, this is an string array of sahpe [# output features], whose values are names of the selected features.
- Return type:
array
- information(print_level: int = 1) None
Print overview information about the options settings and statistics.
- Parameters:
print_level (int (default=1)) – Level of details.
- classmethod load(path: str) BaseBinningProcess
Load binning process from pickle file.
- Parameters:
path (str) – Pickle file path.
Example
>>> from optbinning import BinningProcess >>> binning_process = BinningProcess.load("my_binning_process.pkl")
- plot(variable_names: list[str] | tuple[str] | NDArray | None = None, ncols: int | None = None, figsize: tuple[float, float] | None = None, add_special: bool = True, add_missing: bool = True, show_bin_labels: bool = False, share_metric: bool = True, share_legend: bool = True) tuple[Figure, NDArray]
Plot fitted variables in a grid using their existing binning plots.
- Parameters:
variable_names (list of str or None (default=None)) – Fitted variables to plot, in order. By default, plot the selected variables returned by get_support(names=True).
ncols (int or None (default=None)) – Maximum number of columns in the grid. By default, use the ceiling of the square root of the number of plotted variables.
figsize (tuple or None (default=None)) – Figure size. By default, allocate 6 by 4.5 inches per panel.
add_special (bool (default=True)) – Whether to include special-code bins.
add_missing (bool (default=True)) – Whether to include missing-value bins.
show_bin_labels (bool (default=False)) – Whether to show bin labels instead of bin IDs.
share_metric (bool (default=True)) – Share the secondary metric y-axis across panels, using limits that cover all plotted variables. Count axes remain independent.
share_legend (bool (default=True)) – Show one legend for the whole figure instead of a legend per panel.
- Returns:
fig (matplotlib.figure.Figure) – The figure, which is neither shown nor closed automatically.
axes (numpy.ndarray) – Two-dimensional array of primary axes. Unused panels are hidden; each populated panel also has its existing secondary metric axis.
Notes
Supports standard binary, continuous and multiclass binning tables. Tables are built with default parameters if not already built. Uses the existing default metrics and standard bin layout for each type.
- save(path: str) None
Save binning process to pickle file.
- Parameters:
path (str) – Pickle file path.
- set_output(*, transform=None)
Set output container.
Refer to the user guide for more details and sphx_glr_auto_examples_miscellaneous_plot_set_output.py for an example on how to use the API.
- Parameters:
transform ({"default", "pandas", "polars"}, default=None) –
Configure output of transform and fit_transform.
”default”: Default output format of a transformer
”pandas”: DataFrame output
”polars”: Polars output
None: Transform configuration is unchanged
Added in version 1.4: “polars” option was added.
- Returns:
self – Estimator instance.
- Return type:
estimator instance
- set_params(**params)
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as
Pipeline). The latter have parameters of the form<component>__<parameter>so that it’s possible to update each component of a nested object.- Parameters:
**params (dict) – Estimator parameters.
- Returns:
self – Estimator instance.
- Return type:
estimator instance
- summary() DataFrame
Binning process summary with main statistics for all binned variables.
- Parameters:
df_summary (pandas.DataFrame) – Binning process summary.
- transform(X: NDArray | DataFrame, metric: str | None = None, metric_special: float | str = 0, metric_missing: float | str = 0, show_digits: int = 2, check_input: bool = False) ndarray
Transform given data to metric using bins from each fitted optimal binning.
- Parameters:
X (numpy.ndarray or pandas.DataFrame of shape (n_samples, n_features)) – Training vector, where n_samples is the number of samples.
metric (str or None, (default=None)) – The metric used to transform the input vector. If None, the default transformation metric for each target type is applied. For binary target options are: “woe” (default), “event_rate”, “indices” and “bins”. For continuous target options are: “mean” (default), “indices” and “bins”. For multiclass target options are: “mean_woe” (default), “weighted_mean_woe”, “indices” and “bins”.
metric_special (float or str (default=0)) – The metric value to transform special codes in the input vector. Supported metrics are “empirical” to use the empirical WoE or event rate for a binary target, and any numerical value for other targets.
metric_missing (float or str (default=0)) – The metric value to transform missing values in the input vector. Supported metrics are “empirical” to use the empirical WoE or event rate for a binary target, and any numerical value for other targets.
show_digits (int, optional (default=2)) – The number of significant digits of the bin column. Applies when
metric="bins".check_input (bool (default=False)) – Whether to check input arrays.
- Returns:
X_new (numpy array or pandas.DataFrame, shape = (n_samples,)
n_features_new) – Transformed array.
- transform_disk(input_path: str, output_path: str, chunksize: int, metric: str | None = None, metric_special: float | str = 0, metric_missing: float | str = 0, show_digits: int = 2, **kwargs) Self
Transform given data on disk to metric using bins from each fitted optimal binning. Save to comma-separated values (csv) file.
- Parameters:
input_path (str) – Any valid string path to a file with extension .csv.
output_path (str) – Any valid string path to a file with extension .csv.
chunksize (int) – Rows to read, transform and write at a time.
metric (str or None, (default=None)) – The metric used to transform the input vector. If None, the default transformation metric for each target type is applied. For binary target options are: “woe” (default), “event_rate”, “indices” and “bins”. For continuous target options are: “mean” (default), “indices” and “bins”. For multiclass target options are: “mean_woe” (default), “weighted_mean_woe”, “indices” and “bins”.
metric_special (float or str (default=0)) – The metric value to transform special codes in the input vector. Supported metrics are “empirical” to use the empirical WoE or event rate for a binary target, and any numerical value for other targets.
metric_missing (float or str (default=0)) – The metric value to transform missing values in the input vector. Supported metrics are “empirical” to use the empirical WoE or event rate for a binary target, and any numerical value for other targets.
show_digits (int, optional (default=2)) – The number of significant digits of the bin column. Applies when
metric="bins".**kwargs (keyword arguments) – Keyword arguments for
pandas.read_csv.
- Returns:
self – Fitted binning process.
- Return type:
- update_binned_variable(name: str, optb: BaseOptimalBinning) None
Update optimal binning object for a given variable.
- Parameters:
name (str) – The variable name.
optb (BaseOptimalBinning) – The optimal binning object already fitted.
Plotting several variables
Plot selected variables using their existing binning-table charts:
fig, axes = binning_process.plot()
fig.savefig("binning_overview.png")
By default, the grid uses ceil(sqrt(number of plotted variables)) columns
and enough rows to fit all variables. Override this with ncols=3, for
example. Unused panels are hidden.
Metric y-axes share a common scale by default, covering all plotted variables.
Use share_metric=False for independent metric scales. Bin-count axes and
x-axes remain independent. One shared legend is displayed below the grid;
use share_legend=False to keep individual panel legends.
Choose a subset and its order with variable_names=["age", "income"].
The grid supports standard binary, continuous and multiclass binning tables,
uses their default metrics, and builds tables if needed. It returns a figure
and a two-dimensional array of primary axes without showing or closing them.
Piecewise and two-dimensional binning are outside this interface.
To compose individual plots yourself, build a table and pass existing axes:
fig, ax = plt.subplots()
table = binning_process.get_binned_variable("age").binning_table
table.build()
table.plot(ax=ax)
Import matplotlib.pyplot as plt for the second example. The existing
standalone table.plot() behavior is unchanged.
Example: numerical and categorical features
This synthetic example plots four continuous-valued numerical features and
four categorical features in a three-column grid. The target is binary.
Declare categorical columns explicitly with categorical_variables.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from optbinning import BinningProcess
rng = np.random.default_rng(315)
n = 2000
age = rng.uniform(18, 75, n)
income = rng.lognormal(10.8, 0.5, n)
tenure = rng.uniform(0, 15, n)
balance = rng.lognormal(8, 0.8, n)
region = rng.choice(['North', 'South', 'West'], n)
channel = rng.choice(['Branch', 'Online', 'Partner'], n)
housing = rng.choice(['Owner', 'Renter', 'Other'], n)
employment = rng.choice(['Employed', 'Self-employed', 'Other'], n)
channel_effect = pd.Series(channel).map(
{'Branch': -0.8, 'Online': 0.2, 'Partner': 1.0}).to_numpy()
housing_effect = pd.Series(housing).map(
{'Owner': -0.5, 'Renter': 0.4, 'Other': 0.1}).to_numpy()
employment_effect = pd.Series(employment).map(
{'Employed': -0.4, 'Self-employed': 0.2, 'Other': 0.7}).to_numpy()
logit = ((age - 45) / 20 - (np.log(income) - 10.8)
- (tenure - 7.5) / 8 + channel_effect
+ housing_effect + employment_effect
+ (np.log(balance) - 8) / 2 + 0.4 * (region == 'South'))
y = rng.binomial(1, 1 / (1 + np.exp(-logit)))
X = pd.DataFrame({
'Age': age, 'Income': income, 'Tenure': tenure,
'Channel': channel, 'Housing': housing, 'Employment': employment,
'Balance': balance, 'Region': region})
categorical = ['Channel', 'Housing', 'Employment', 'Region']
process = BinningProcess(
variable_names=list(X.columns), categorical_variables=categorical,
max_n_bins=4)
process.fit(X, y)
fig, axes = process.plot(
figsize=(18, 14), add_special=False, add_missing=False)
# Customize categorical labels through the returned axes.
for ax, name in zip(axes.flat, X.columns):
if name not in categorical:
continue
groups = process.get_binned_variable(name).splits
ax.set_xticks(
np.arange(len(groups)), [', '.join(map(str, group)) for group in groups])
ax.set_xlabel('Category')
fig.savefig('binning_mixed_features.png', dpi=120)
plt.close(fig)
Eight features fill two complete rows and two panels in the last row. The unused ninth panel is hidden automatically. Numerical features use bin IDs; categorical features use names set through the returned axes. Stacked bars show event/non-event counts; black curves show WoE on each panel’s right axis, with a shared scale. Special and missing bins are hidden because this synthetic dataset contains neither.
No feature-selection criteria are configured here, so plot() includes
all eight fitted variables. To include all fitted variables even when selection
criteria are configured, pass variable_names=process.variable_names.
For an interactive display, replace plt.close(fig) with plt.show().