### Install OptBinning from Source Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/installation.rst Install OptBinning directly from its source code repository. This involves cloning the repository and then running the setup script. ```text cd optbinning python setup.py install ``` -------------------------------- ### Install OptBinning Release from Downloaded Archive Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/installation.rst Install a specific release of OptBinning by first downloading the archive from the releases page and then running the setup script. ```text python setup.py install ``` -------------------------------- ### Install OptBinning Source: https://context7.com/guillermo-navas-palencia/optbinning/llms.txt Standard installation using pip. Additional packages can be installed for distributed support or specific solvers. ```bash # Standard install pip install optbinning # With batch/streaming support pip install optbinning[distributed] # With ECOS solver support pip install optbinning[ecos] # From source git clone https://github.com/guillermo-navas-palencia/optbinning.git cd optbinning python setup.py install ``` -------------------------------- ### Install OptBinning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/README.rst Install the current release of OptBinning from PyPI. For advanced features like batch and stream binning, use the `distributed` option. To include the `ecos` solver, use the `ecos` option. ```text pip install optbinning ``` ```text pip install optbinning[distributed] ``` ```text pip install optbinning[ecos] ``` -------------------------------- ### Install OptBinning Release with Pip Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/installation.rst Use this command to install the latest stable release of OptBinning from the Python Package Index (PyPI). ```text pip install optbinning ``` -------------------------------- ### Optbinning Information Output Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/README.rst Example output from the `information` method, detailing the optbinning version, copyright, and configuration options for prebinning, solver, and divergence. ```text optbinning (Version 0.21.0) Copyright (c) 2019-2025 Guillermo Navas-Palencia, Apache License 2.0 Begin options name mean radius * U dtype numerical * d prebinning_method cart * d solver cp * d divergence iv * d max_n_prebins 20 * d min_prebin_size 0.05 * d min_n_bins no * d max_n_bins no * d min_bin_size no * d max_bin_size no * d min_bin_n_nonevent no * d max_bin_n_nonevent no * d min_bin_n_event no * d ``` -------------------------------- ### Binning Table Example Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/README.rst A sample binning table displaying binned data, counts, event rates, WoE, IV, and JS divergence. ```text Bin Count Count (%) Non-event Event Event rate WoE IV JS 0 [-inf, 11.43) 118 0.207381 3 115 0.974576 -3.12517 0.962483 0.087205 1 [11.43, 12.33) 79 0.138840 3 76 0.962025 -2.71097 0.538763 0.052198 2 [12.33, 13.09) 68 0.119508 7 61 0.897059 -1.64381 0.226599 0.025513 3 [13.09, 13.70) 49 0.086116 10 39 0.795918 -0.839827 0.052131 0.006331 4 [13.70, 15.05) 83 0.145870 28 55 0.662651 -0.153979 0.003385 0.000423 5 [15.05, 16.93) 54 0.094903 44 10 0.185185 2.00275 0.359566 0.038678 6 [16.93, inf) 118 0.207381 117 1 0.008475 5.28332 2.900997 0.183436 7 Special 0 0.000000 0 0 0.000000 0 0.000000 0.000000 8 Missing 0 0.000000 0 0 0.000000 0 0.000000 0.000000 Totals 569 1.000000 212 357 0.627417 5.043925 0.393784 ``` -------------------------------- ### Apply Sample Weights Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_continuous.ipynb Create and apply sample weights to influence the binning process. This example increases the weights for values less than 10. ```python sample_weight = np.ones(len(x)) sample_weight[x < 10] = 5 ``` ```python optb = ContinuousOptimalBinning(name=variable, dtype="numerical", monotonic_trend="descending") optb.fit(x, y, sample_weight=sample_weight) ``` ```python optb.binning_table.build() ``` -------------------------------- ### Load Data and Scorecard for Counterfactuals Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/README.rst Imports necessary libraries and loads a dataset along with a pre-developed scorecard. This is the setup for generating counterfactual explanations. ```python import pandas as pd from optbinning import Scorecard from optbinning.scorecard import Counterfactual from sklearn.datasets import load_boston ``` -------------------------------- ### Initialize Multiclass Optimal Binning with No Monotonic Trend Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_multiclass.ipynb Initialize `MulticlassOptimalBinning` with `monotonic_trend=None` to let the solver determine the best trend. This is a good starting point for exploring monotonic trends. ```python optb = MulticlassOptimalBinning(name=variable, solver="mip", monotonic_trend=None) optb.fit(x, y) ``` -------------------------------- ### Get and Build Binning Table for 'tenure' Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_process_telco_churn.ipynb Retrieves and builds the binning table for the 'tenure' variable to analyze its relationship with churn. This is useful for understanding how customer tenure affects churn probability. ```python optb = binning_process.get_binned_variable("tenure") optb.binning_table.build() ``` -------------------------------- ### Get binning process summary Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_process_sklearn_pipeline.ipynb Generate and display a summary table of the binning process for each variable, including statistics like name, type, status, selection, number of bins, WOE, and quality score. ```python binning_process.summary() ``` -------------------------------- ### Initialize OptimalBinning with CP Solver and Time Limit Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_localsolver.ipynb Configure the OptimalBinning class to use the 'cp' solver with a maximum pre-bin count and a 5-second time limit. This is useful when LocalSolver is not available or for initial testing. ```python optb = OptimalBinning(name=variable, dtype="numerical", solver="cp", max_n_prebins=100, min_prebin_size=0.001, time_limit=5) ``` -------------------------------- ### Get Binning Table Type Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_multiclass.ipynb Checks the type of the binning table object. ```python type(binning_table) ``` -------------------------------- ### Initialize OptimalPWBinning with Gradient Boosting Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_piecewise_binary.ipynb Initialize the OptimalPWBinning class with a GradientBoostingClassifier estimator. This sets up the binning process for a specific variable. ```python variable = "mean texture" x = df[variable].values y = data.target ``` ```python optb = OptimalPWBinning(name=variable, estimator=GradientBoostingClassifier()) optb.fit(x, y, lb=0.001, ub=0.999) ``` -------------------------------- ### Get Optimal Splits from SBOptimalBinning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_under_uncertainty.ipynb Access the calculated optimal splits determined by the SBOptimalBinning algorithm. These splits define the bin boundaries. ```python sboptb.splits ``` -------------------------------- ### Get Supported Variables Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_process_telco_churn.ipynb Retrieves the names of variables that have been selected as supportive by the binning process. This is useful for feature selection in predictive modeling. ```python binning_process.get_support(names=True) ``` -------------------------------- ### Import and instantiate OptimalBinningSketch Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_sketch_binary.ipynb Import the OptimalBinningSketch class and create an instance. Configure it with the variable name, data type, sketch type ('gk'), desired absolute precision (eps), minimum bin size, and the constraint programming solver. ```python from optbinning import OptimalBinningSketch ``` ```python optbsketch = OptimalBinningSketch(name=variable, dtype="numerical", sketch="gk", eps=1e-4, min_bin_size=0.05, solver="cp") ``` -------------------------------- ### Import and configure OptimalBinning with LocalSolver Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_localsolver.ipynb Imports the OptimalBinning class and instantiates it for numerical data, specifying 'ls' as the solver. Configures parameters like max_n_prebins, min_prebin_size, and time_limit for the LocalSolver. ```python from optbinning import OptimalBinning ``` ```python optb = OptimalBinning(name=variable, dtype="numerical", solver="ls", max_n_prebins=100, min_prebin_size=0.001, time_limit=20) ``` -------------------------------- ### Initialize and Fit OptimalPWBinning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_piecewise_binary.ipynb Initializes the OptimalPWBinning class with the variable name, defined special codes, and the solver type. It then fits the binning model to the prepared data 'x' and 'y', specifying the lower and upper bounds for the binning process. ```python optb = OptimalPWBinning(name=variable, special_codes=special_codes, solver="osqp") optb.fit(x, y, lb=0, ub=1) ``` -------------------------------- ### Initialize and Fit OptimalBinning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_under_uncertainty.ipynb Initialize the OptimalBinning class with specified constraints (monotonic trend and minimum bin size) and fit it to the data. ```python optb1 = OptimalBinning(monotonic_trend="descending", min_bin_size=0.05) optb1.fit(x1, y1) ``` -------------------------------- ### Binning Table Analysis Results Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/README.rst Example output of the `analysis` method, showing general metrics, monotonic trend, and significance tests between consecutive bins. ```text --------------------------------------------- OptimalBinning: Binary Binning Table Analysis --------------------------------------------- General metrics Gini index 0.87541620 IV (Jeffrey) 5.04392547 JS (Jensen-Shannon) 0.39378376 Hellinger 0.47248971 Triangular 1.25592041 KS 0.72862164 HHI 0.15727342 HHI (normalized) 0.05193260 Cramer's V 0.80066760 Quality score 0.00000000 Monotonic trend descending Significance tests Bin A Bin B t-statistic p-value P[A > B] P[B > A] 0 1 0.252432 6.153679e-01 0.684380 3.156202e-01 1 2 2.432829 1.188183e-01 0.948125 5.187465e-02 2 3 2.345804 1.256207e-01 0.937874 6.212635e-02 3 4 2.669235 1.023052e-01 0.955269 4.473083e-02 4 5 29.910964 4.523477e-08 1.000000 9.814594e-12 5 6 19.324617 1.102754e-05 0.999999 1.216668e-06 ``` -------------------------------- ### Initialize and Fit 2D Optimal Binning (CP Solver with CART Strategy) Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_2d.ipynb Initializes the OptimalBinning2D class using the CP solver and the CART strategy for pre-binning. This approach can accelerate the solution at the cost of potentially worsening the total IV. ```python optb = OptimalBinning2D(name_x=variable1, name_y=variable2, solver="cp", strategy="cart", monotonic_trend_x="descending", monotonic_trend_y="descending", max_n_prebins_x=10, max_n_prebins_y=10, min_bin_size=0.05, special_codes_x=special_codes_x, special_codes_y=special_codes_y) optb.fit(x, y, z) ``` -------------------------------- ### Piecewise Binary Transformation with Special Codes Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_piecewise_binary.ipynb Example of creating a piecewise binary transformation, specifying special codes for handling missing values. The solver and verbosity are also configured. ```python from optbinning import OptimalBins, BinningProcess # Define special codes special_codes = [-999, -998] # Create a BinningProcess with piecewise binary transformation binning_process = BinningProcess(variable_names=['x'], variable_type='categorical', missing_treatment='separate', special_codes=special_codes, solver='osqp', verbose=True) ``` -------------------------------- ### Initialize OptimalPWBinning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_piecewise_binary.ipynb Imports and instantiates the OptimalPWBinning class, which is specifically designed for numerical variables and binary targets. ```python from optbinning import OptimalPWBinning ``` ```python optb = OptimalPWBinning(name=variable) ``` -------------------------------- ### Initialize OptimalPWBinning with User-Defined Fixed Splits Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_piecewise_binary.ipynb Initialize OptimalPWBinning using user-defined split points, with some splits fixed to ensure they appear in the final binning solution. This allows for incorporating prior knowledge or business rules into the binning process. ```python user_splits = [ 14, 15, 16, 17, 20, 21, 22, 27] user_splits_fixed = [False, True, True, False, False, False, False, False] ``` ```python optb = OptimalPWBinning(name=variable, user_splits=user_splits, user_splits_fixed=user_splits_fixed) optb.fit(x, y) ``` -------------------------------- ### Initialize and Fit OptimalBinning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_under_uncertainty.ipynb Initialize the OptimalBinning class with specified parameters and fit it to the data. ```python optb = OptimalBinning(monotonic_trend="descending", min_bin_size=0.05) optb.fit(x0, y0) ``` -------------------------------- ### Generate Diverse Counterfactuals with Constraints Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_counterfactual_binary_target.ipynb Generate counterfactual examples for a binary target, enforcing diversity in both features and feature values using hard constraints. This ensures unique combinations of changes. ```python cf.generate(query=query, y=1, outcome_type="binary", n_cf=3, max_changes=4, hard_constraints=["diversity_features", "diversity_values"], time_limit=15 ).display(show_only_changes=True, show_outcome=True) ``` -------------------------------- ### Print Information Overview Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/README.rst Display overview information about the optbinning settings, problem statistics, and computation results using the `information` method with `print_level=2`. ```python >>> optb.information(print_level=2) ``` -------------------------------- ### Load Data and Initialize OptimalBinning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/README.rst Load a dataset using scikit-learn and prepare it for optimal binning. Import and instantiate the OptimalBinning class, specifying the variable name, data type, and solver. ```python import pandas as pd from sklearn.datasets import load_breast_cancer data = load_breast_cancer() df = pd.DataFrame(data.data, columns=data.feature_names) variable = "mean radius" x = df[variable].values y = data.target ``` ```python from optbinning import OptimalBinning optb = OptimalBinning(name=variable, dtype="numerical", solver="cp") optb.fit(x, y) ``` -------------------------------- ### Generate Detailed PSI Variable Table Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_scorecard_monitoring.ipynb Use psi_variable_table with style='detailed' to get a comprehensive PSI report at the characteristic level, including bin counts and percentages for both actual (A) and expected (E) data. ```python monitoring.psi_variable_table(style="detailed") ``` -------------------------------- ### Initialize OptimalPWBinning with Verbose Output Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_piecewise_binary.ipynb Initializes the OptimalPWBinning class with the verbose option enabled. This will print detailed logs during the fitting process, which can be useful for debugging. ```python optb = OptimalPWBinning(name=variable, solver="osqp", verbose=True) optb.fit(x, y, lb=0, ub=1) ``` -------------------------------- ### Initialize and Fit OptimalBinning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_under_uncertainty.ipynb Initializes an OptimalBinning object with specified parameters like monotonic trend and minimum bin size, then fits it to the data. ```python optb2 = OptimalBinning(monotonic_trend="descending", min_bin_size=0.05) optb2.fit(x2, y2) ``` -------------------------------- ### Counterfactual Generation Log Output Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_counterfactual_continuous_target.ipynb This log output details the progression of a counterfactual explanation generation process. It shows the start and end times, status, and duration for various stages including parameter checking, optimizer execution, and post-processing. ```log 2024-01-15 00:15:11,109 | INFO : Counterfactual generation started. 2024-01-15 00:15:11,114 | INFO : Options: check parameters. 2024-01-15 00:15:11,125 | INFO : Options: check objectives and constraints. 2024-01-15 00:15:11,127 | INFO : Optimizer started. 2024-01-15 00:15:11,129 | INFO : Optimizer: build model... 2024-01-15 00:15:11,294 | INFO : Optimizer: solve... 2024-01-15 00:15:41,694 | INFO : Optimizer terminated. Time: 30.5651s 2024-01-15 00:15:41,696 | INFO : Post-processing started. 2024-01-15 00:15:41,716 | INFO : Post-processing terminated. Time: 0.0192s 2024-01-15 00:15:41,717 | INFO : Counterfactual generation terminated. Status: FEASIBLE. Time: 30.6084s ``` -------------------------------- ### Optimal Piecewise Polynomial Binning Source: https://context7.com/guillermo-navas-palencia/optbinning/llms.txt Fits a piecewise polynomial regression within each bin for binary targets, useful for smooth probability calibration. Requires `numpy` and `optbinning.OptimalPWBinning`. The `fit` method trains the binning, and `transform` can be used to get predicted probabilities. ```python import numpy as np from optbinning import OptimalPWBinning rng = np.random.default_rng(0) x = rng.uniform(0, 10, 500) y = (rng.logistic(x - 5, 1) > 0).astype(int) optpwb = OptimalPWBinning( name="score", degree=1, # piecewise linear continuous=True, # continuous at breakpoints objective="l2", monotonic_trend="ascending", max_n_prebins=20, min_bin_size=0.05, ) optpwb.fit(x, y) print(optpwb.status) # OPTIMAL print(optpwb.splits) # Piecewise binning table with polynomial coefficients per bin df_table = optpwb.binning_table.build() print(df_table) # Transform to predicted probability (smooth) x_proba = optpwb.transform(x, metric="event_rate") ``` -------------------------------- ### Initialize and Fit 2D Optimal Binning (CP Solver) Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_2d.ipynb Initializes the OptimalBinning2D class with specific parameters for the CP solver and fits the model to the data. ```python optb = OptimalBinning2D(name_x=variable1, name_y=variable2, solver="cp", strategy="cart", monotonic_trend_x="descending", monotonic_trend_y="descending", max_n_prebins_x=20, max_n_prebins_y=20, min_bin_size=0.05, special_codes_x=special_codes_x, special_codes_y=special_codes_y) optb.fit(x, y, z) ``` -------------------------------- ### Initialize OptimalBinning Solver with Time Limit Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_localsolver.ipynb Initializes the OptimalBinning solver for a numerical variable with a binary target. It specifies the solver type ('cp'), maximum number of pre-bins, minimum pre-bin size, and sets a time limit for the optimization process. ```python optb = OptimalBinning(name=variable, dtype="numerical", solver="cp", max_n_prebins=100, min_prebin_size=0.001, time_limit=200) ``` -------------------------------- ### Initialize Scorecard Monitoring Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_scorecard_monitoring.ipynb Sets up the ScorecardMonitoring instance with a specified PSI method ('cart') and number of bins (10). ```python monitoring = ScorecardMonitoring(scorecard=scorecard, psi_method="cart", psi_n_bins=10) ``` -------------------------------- ### Instantiate BinningProcess and Classifiers Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_process_FICO_xAI.ipynb Creates a BinningProcess object with specified parameters and initializes pipelines for logistic regression (explainable) and a Gradient Boosting Classifier (black-box). ```python binning_process = BinningProcess(variable_names, special_codes=special_codes, binning_fit_params=binning_fit_params) ``` ```python clf1 = Pipeline(steps=[('binning_process', binning_process), ('classifier', LogisticRegression(solver="lbfgs"))]) clf2 = LogisticRegression(solver="lbfgs") clf3 = GradientBoostingClassifier() ``` -------------------------------- ### Initialize OptimalBinning with Monotonic Trend and Min Bin Size Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_under_uncertainty.ipynb Sets up an OptimalBinning object with a descending monotonic trend and a minimum bin size of 0.05. This is useful for creating bins that respect a specific order and size constraint. ```python optb0 = OptimalBinning(monotonic_trend="descending", min_bin_size=0.05) optb0.fit(x0, y0) ``` -------------------------------- ### Initialize and Fit 2D Optimal Binning (MIP Solver) Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_2d.ipynb Initializes the OptimalBinning2D class with specific parameters for the MIP solver and fits the data. This is useful for finding an optimal binning solution when computational resources allow. ```python optb = OptimalBinning2D(name_x='ExternalRiskEstimate', name_y='AverageMInFile', solver='mip', special_codes_x=[-9, -8, -7], special_codes_y=[-9, -8, -7]) optb.fit(x, y, z) ``` -------------------------------- ### Initialize Data for Transformation Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_sketch_binary.ipynb Prepare a list of numerical data points to be transformed. ```python x = [0.2, 0.31, 0.21, 0.12, 0.16, 0.41, 0.65, 0.8] ``` -------------------------------- ### Build Binning Table for Scenario 1 Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_under_uncertainty.ipynb Construct the binning table for scenario 1. This table summarizes the binning process and key statistics. ```python bt1 = sboptb.binning_table_scenario(scenario_id=1) bt1.build() ``` -------------------------------- ### Initialize and Fit OptimalPWBinning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_piecewise_binary.ipynb Initialize an OptimalPWBinning object for a specific variable and fit it to the data. ```python optb = OptimalPWBinning(name=variable) optb.fit(x, y) ``` -------------------------------- ### Build Binning Table for Scenario 0 Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_under_uncertainty.ipynb Initializes and builds a binning table for a specific scenario (scenario_id=0). ```python bt0 = sboptb.binning_table_scenario(scenario_id=0) bt0.build() ``` -------------------------------- ### Initialize OptimalBinningSketch for Distributed Data Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_sketch_binary.ipynb Set up file paths for partitioned data stored in parquet format. This is the first step in processing large datasets across multiple files without centralization. ```python filepaths = ["data/df1.parquet.gzip", "data/df2.parquet.gzip", "data/df3.parquet.gzip"] variable = "EXT_SOURCE_3" target = "TARGET" ``` -------------------------------- ### Initialize ContinuousOptimalBinning2D Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_continuous_2d.ipynb Imports the ContinuousOptimalBinning2D class and instantiates it, specifying the names of the x and y variables and the solver. ```python from optbinning import ContinuousOptimalBinning2D ``` ```python optb = ContinuousOptimalBinning2D(name_x=variable1, name_y=variable2, solver="cp") ``` -------------------------------- ### Initialize and Fit OptimalBinning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary.ipynb Initializes the OptimalBinning object with the variable name, data type, solver, and special codes. Then, it fits the binning model to the data. ```python optb = OptimalBinning(name=variable, dtype="numerical", solver="mip", special_codes=special_codes) optb.fit(x, y) ``` -------------------------------- ### Instantiate and Fit SBOptimalBinning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_under_uncertainty.ipynb Instantiate the SBOptimalBinning object with specified constraints (monotonic trend and minimum bin size) and fit it to the prepared data. ```python sboptb = SBOptimalBinning(monotonic_trend="descending", min_bin_size=0.05) sboptb.fit(X, Y) ``` -------------------------------- ### Initialize ContinuousOptimalBinning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_continuous.ipynb Initialize the ContinuousOptimalBinning with specified parameters. This configuration uses a descending monotonic trend and y-quantile outlier detection. ```python ContinuousOptimalBinning(monotonic_trend='descending', name='LSTAT', outlier_detector='yquantile', outlier_params={ 'n_bins': 10, 'outlier_detector': 'range', 'outlier_params': {'method': 'HDI'} }, verbose=True) ``` -------------------------------- ### Initialize and Fit Continuous Optimal Binning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_continuous.ipynb Prepare data for continuous binning by selecting a variable and initializing `ContinuousOptimalBinning`. The `monotonic_trend` can be set to 'auto' for automatic selection or a specific trend like 'ascending' or 'descending'. ```python variable = "INDUS" x = df[variable].values ``` ```python optb = ContinuousOptimalBinning(name=variable, dtype="numerical", monotonic_trend="auto") optb.fit(x, y) ``` -------------------------------- ### Display MulticlassOptimalBinning Information Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_multiclass.ipynb Prints detailed information about the binning process, including options, solver statistics, and timing. Set print_level to 2 for comprehensive output. ```python optb.information(print_level=2) ``` -------------------------------- ### Build Binning Table with OptimalBinning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_under_uncertainty.ipynb Build the binning table after fitting the OptimalBinning model. This table contains the final binned data and statistics. ```python optb1.binning_table.build() ``` -------------------------------- ### Initialize OptimalBinning Object Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary.ipynb Imports the OptimalBinning class and instantiates an object, specifying the variable name, data type, and the solver to use. ```python from optbinning import OptimalBinning ``` ```python optb = OptimalBinning(name=variable, dtype="numerical", solver="cp") ``` -------------------------------- ### Instantiate and Fit Scorecard Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/README.rst Initializes a Scorecard with a BinningProcess and HuberRegressor, specifying scaling methods and reverse mode. Fit the scorecard to the data. ```python binning_process = BinningProcess(variable_names) estimator = HuberRegressor(max_iter=200) scorecard = Scorecard(binning_process=binning_process, estimator=estimator, scaling_method="min_max", scaling_method_params={"min": 0, "max": 100}, reverse_scorecard=True) scorecard.fit(X, y) ``` -------------------------------- ### Build and Display Binning Table Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_continuous.ipynb After fitting the optimal binning, build the binning table to view the statistics for each bin, including counts, means, WoE, and IV. ```python binning_table = optb.binning_table binning_table.build() ``` -------------------------------- ### Instantiate and Fit Scorecard Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_scorecard_monitoring.ipynb Initializes a Scorecard object with the binning process and estimator, then fits it to the training data. ```python scorecard = Scorecard(binning_process=binning_process, estimator=estimator, scaling_method="min_max", scaling_method_params={"min": 0, "max": 100}) scorecard.fit(X_train, y_train, metric_special="empirical", metric_missing="empirical") ``` -------------------------------- ### Print SBOptimalBinning Information Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_under_uncertainty.ipynb Display detailed information about the SBOptimalBinning configuration, status, and solver statistics. Use print_level=2 for comprehensive output. ```python sboptb.information(print_level=2) ``` -------------------------------- ### Build and Display Binning Table Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_2d.ipynb Builds the binning table for the fitted 2D OptimalBinning object and displays it. The table includes bin definitions, counts, event rates, WoE, and IV. ```python optb.binning_table.build() ``` ```text Result: Bin x Bin y Count Count (%) Non-event Event \ 0 (-inf, 63.50) (-inf, 54.50) 749 0.071613 87 662 1 [63.50, 70.50) (-inf, 54.50) 765 0.073143 187 578 2 [70.50, 78.50) (-inf, 64.50) 815 0.077923 343 472 3 [78.50, 80.50) (-inf, inf) 588 0.056220 405 183 4 [80.50, inf) (-inf, 74.50) 563 0.053829 405 158 5 (-inf, 59.50) [54.50, inf) 746 0.071326 131 615 6 [59.50, 67.50) [54.50, 81.50) 828 0.079166 213 615 7 [67.50, 70.50) [54.50, inf) 735 0.070274 309 426 8 [70.50, 75.50) [64.50, inf) 1049 0.100296 596 453 9 [75.50, 78.50) [64.50, inf) 549 0.052491 372 177 10 [80.50, 84.50) [74.50, inf) 668 0.063868 528 140 11 [84.50, inf) [74.50, inf) 1080 0.103260 917 163 12 [59.50, 67.50) [81.50, inf) 726 0.069414 240 486 13 Special Special 598 0.057176 267 331 14 Missing Missing 0 0.000000 0 0 Totals 10459 1.000000 5000 5459 Event rate WoE IV JS 0 0.883845 -1.941530 0.201662 0.021871 1 0.755556 -1.040638 0.071263 0.008527 2 0.579141 -0.231421 0.004134 0.000516 3 0.311224 0.882229 0.041886 0.005072 4 0.280639 1.029120 0.053573 0.006416 5 0.824397 -1.458597 0.126107 0.014500 6 0.742754 -0.972502 0.068132 0.008196 7 0.579592 -0.233270 0.003787 0.000472 8 0.431840 0.362176 0.013117 0.001631 9 0.322404 0.830572 0.034864 0.004237 10 0.209581 1.415282 0.113158 0.013071 11 0.150926 1.815185 0.278705 0.030726 12 0.669421 -0.617742 0.025344 0.003119 13 0.553512 -0.127042 0.000919 0.000115 14 0.000000 0.000000 0.000000 0.000000 Totals 0.521943 1.036652 0.118468 ``` -------------------------------- ### Initialize and Fit BinningProcess Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_process_telco_churn.ipynb Initializes a BinningProcess object with specified variable names, categorical variables, and selection criteria. Then, fits the process to the input data (X) and target (y). ```python binning_process = BinningProcess(variable_names, categorical_variables=categorical_variables, selection_criteria=selection_criteria) binning_process.fit(X, y) ``` -------------------------------- ### Instantiate OptimalBinning2D Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_2d.ipynb Imports the OptimalBinning2D class and instantiates it, specifying the names of the x and y variables and the solver type (constraint programming). ```python from optbinning import OptimalBinning2D ``` ```python optb = OptimalBinning2D(name_x=variable1, name_y=variable2, solver="cp") ``` -------------------------------- ### Initialize and Fit OptimalBinning2D Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_2d.ipynb Initialize the OptimalBinning2D class with specified variable names, data types, and the maximum number of bins. Fit the model to the prepared data. ```python optb = OptimalBinning2D(name_x=variable1, name_y=variable2, dtype_x="categorical", dtype_y="categorical", max_n_bins=10) optb.fit(x, y, z) ``` -------------------------------- ### Import Libraries for Optbinning and Machine Learning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_process_FICO_update_binning.ipynb Imports core components from optbinning, LightGBM, and scikit-learn for classification and model evaluation. ```python from lightgbm import LGBMClassifier from optbinning import BinningProcess from optbinning import OptimalPWBinning from sklearn.linear_model import LogisticRegression from sklearn.ensemble import GradientBoostingClassifier from sklearn.metrics import classification_report from sklearn.metrics import auc, roc_auc_score, roc_curve from sklearn.model_selection import train_test_split ``` -------------------------------- ### Instantiate BinningProcess and Scikit-learn Pipeline Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_process_sklearn_pipeline.ipynb Create a BinningProcess object and then a Scikit-learn Pipeline that includes the binning process as a transformer followed by a Linear Regression estimator. ```python binning_process = BinningProcess(variable_names, categorical_variables=categorical_variables) ``` ```python lr = Pipeline(steps=[('binning_process', binning_process), ('regressor', LinearRegression())]) ``` -------------------------------- ### Initialize OptimalBinning2D with Gamma Regularization Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_2d.ipynb Initialize OptimalBinning2D with a regularization parameter 'gamma' to reduce the difference between the largest and smallest bins. This helps in producing more homogeneous bins. Larger 'gamma' values specify stronger regularization. ```python optb = OptimalBinning2D(name_x=variable1, name_y=variable2, gamma=600) optb.fit(x, y, z) ``` -------------------------------- ### Instantiate Scorecard Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_scorecard_binary_target.ipynb Instantiate a Scorecard class with a binning process, an estimator, and an optional scaling method. ```python scorecard = Scorecard(binning_process=binning_process, estimator=estimator, scaling_method="min_max", scaling_method_params={"min": 300, "max": 850}) ``` -------------------------------- ### Initialize ContinuousOptimalBinning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_continuous.ipynb Imports the ContinuousOptimalBinning class and instantiates it with the variable name and data type. ```python from optbinning import ContinuousOptimalBinning ``` ```python optb = ContinuousOptimalBinning(name=variable, dtype="numerical") ``` -------------------------------- ### Initialize Binning Process Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_scorecard_monitoring.ipynb Creates a BinningProcess object with specified variable names, special codes, and selection criteria. ```python binning_process = BinningProcess(variable_names, special_codes=special_codes, selection_criteria=selection_criteria) ``` -------------------------------- ### Initialize OptimalBinning with Increased Time Limit Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_localsolver.ipynb Re-initialize the OptimalBinning class with a longer time limit (30 seconds) to allow the 'cp' solver more time to find a feasible solution. This is useful when the initial time limit results in an 'UNKNOWN' status. ```python optb = OptimalBinning(name=variable, dtype="numerical", solver="cp", max_n_prebins=100, min_prebin_size=0.001, time_limit=30) ``` -------------------------------- ### Initialize ScorecardMonitoring Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_scorecard_monitoring.ipynb Instantiate ScorecardMonitoring with a fitted scorecard, PSI method, number of bins, and verbosity level. Use this to analyze scorecard discrimination and data distribution differences between train and test sets. ```python monitoring = ScorecardMonitoring(scorecard=scorecard, psi_method="cart", psi_n_bins=10, verbose=True) ``` -------------------------------- ### Build SBOptimalBinning Table Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_under_uncertainty.ipynb Construct and display the binning table for the SBOptimalBinning results. This table summarizes the binned data across all scenarios. ```python sboptb.binning_table.build() ``` -------------------------------- ### Initialize OptimalBinning with 'auto' trend Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_large_scale.ipynb Initializes the OptimalBinning object with numerical data type, 'cp' solver, 'auto' monotonic trend, and specific pre-binning and time limit parameters for large-scale optimization. ```python from optbinning import OptimalBinning ``` ```python optb = OptimalBinning(name=variable, dtype="numerical", solver="cp", monotonic_trend="auto", max_n_prebins=100, min_prebin_size=0.001, time_limit=200) ``` -------------------------------- ### Build Binning Table from OptimalBinning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_under_uncertainty.ipynb Constructs the binning table using the fitted OptimalBinning object, applying the specified constraints. ```python optb0.binning_table.build() ``` -------------------------------- ### Initialize and Fit MulticlassOptimalBinning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_multiclass.ipynb Initialize the MulticlassOptimalBinning class with specified parameters and fit it to the data. This is useful when you need to enforce specific monotonic trends for different classes or use a particular solver. ```python optb = MulticlassOptimalBinning(name=variable, solver="mip", monotonic_trend=["ascending", "auto", None], verbose=True) optb.fit(x, y) ``` -------------------------------- ### Initializing and Fitting OptimalBinning2D Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_2d.ipynb Initialize and fit a 2D OptimalBinning object with specified variables, data types, and monotonic trends. This prepares the binning object for data transformation. ```python variable1 = "AMT_INCOME_TOTAL" variable2 = "NAME_INCOME_TYPE" x = df[variable1].values y = df[variable2].values ``` ```python optb = OptimalBinning2D(name_x=variable1, name_y=variable2, dtype_x="numerical", dtype_y="categorical", monotonic_trend_x="descending", monotonic_trend_y="ascending") optb.fit(x, y, z) ``` -------------------------------- ### Initialize and Fit 2D Optimal Binning (MIP Solver) Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_2d.ipynb Initializes and fits a 2D OptimalBinning object using the MIP solver. This is an alternative to the CP solver, offering different performance characteristics. ```python optb = OptimalBinning2D(name_x=variable1, name_y=variable2, solver="mip", monotonic_trend_x="descending", monotonic_trend_y="descending", max_n_prebins_x=20, max_n_prebins_y=20, min_bin_size=0.05, special_codes_x=special_codes_x, special_codes_y=special_codes_y) optb.fit(x, y, z) ``` -------------------------------- ### Initialize and Fit 2D Optimal Binning (MIP Solver) Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_2d.ipynb Initializes and fits a 2D OptimalBinning object using the MIP (Mixed-Integer Programming) solver. This is an alternative to the CP solver for optimization. ```python optb = OptimalBinning2D(name_x=variable1, name_y=variable2, solver="mip", monotonic_trend_x="descending", monotonic_trend_y="descending", max_n_prebins_x=10, max_n_prebins_y=10, min_bin_size=0.05, special_codes_x=special_codes_x, special_codes_y=special_codes_y) optb.fit(x, y, z) ``` ```text Result: OptimalBinning2D(max_n_prebins_x=10, max_n_prebins_y=10, min_bin_size=0.05, ``` -------------------------------- ### Initialize OptimalPWBinning with Convex Monotonic Trend Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_piecewise_binary.ipynb Initialize OptimalPWBinning, forcing a 'convex' monotonic trend for the event rate. This is useful when business constraints require a specific shape for the event rate curve. ```python optb = OptimalPWBinning(name=variable, estimator=GradientBoostingClassifier(), monotonic_trend="convex") optb.fit(x, y, lb=0.001, ub=0.999) ``` -------------------------------- ### Initialize and Fit 2D Optimal Binning (CP Solver) Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_2d.ipynb Initializes and fits a 2D OptimalBinning object using the CP (Constraint Programming) solver. Configures monotonic trends, pre-binning, and special codes. ```python optb = OptimalBinning2D(name_x=variable1, name_y=variable2, solver="cp", monotonic_trend_x="descending", monotonic_trend_y="descending", max_n_prebins_x=10, max_n_prebins_y=10, min_bin_size=0.05, special_codes_x=special_codes_x, special_codes_y=special_codes_y) optb.fit(x, y, z) ``` -------------------------------- ### Display Minimal Information (print_level=0) Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary.ipynb Print minimal information about the binning process, including the header, variable name, status, and total time. This is useful for a quick overview. ```python optb.information(print_level=0) ``` -------------------------------- ### Instantiate BinningProcess Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_scorecard_binary_target.ipynb Initializes a BinningProcess object with variable names, special codes, and selection criteria for data binning. ```python binning_process = BinningProcess(variable_names, special_codes=special_codes, ``` -------------------------------- ### Initialize and Train a Scorecard Model Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_counterfactual_continuous_target.ipynb Initializes a BinningProcess and a HuberRegressor, then configures and trains a Scorecard model with specified scaling methods and parameters. ```python binning_process = BinningProcess(variable_names) estimator = HuberRegressor(max_iter=200) scorecard = Scorecard(binning_process=binning_process, estimator=estimator, scaling_method="min_max", scaling_method_params={"min": 0, "max": 100}, reverse_scorecard=True,verbose=True) scorecard.fit(X, y) ``` -------------------------------- ### Enable Verbose Output for Debugging Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary.ipynb Set the `verbose` option to `True` when initializing `OptimalBinning` to print detailed information about each step of the computation. This is useful for debugging and understanding the binning process. ```python optb = OptimalBinning(name=variable, dtype="numerical", solver="mip", verbose=True) optb.fit(x, y) ``` -------------------------------- ### Prepare Data for SBOptimalBinning Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binary_under_uncertainty.ipynb Prepare the input data (X and Y) for the SBOptimalBinning class. Ensure data is in a suitable format for fitting. ```python X = [x0, x1, x2] Y = [y0, y1, y2] ``` -------------------------------- ### Build and Display Binning Table Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_continuous.ipynb Generates and displays the binning table, which includes statistics for each bin. The table is built using the 'build' method. ```python binning_table = optb.binning_table ``` ```python type(binning_table) ``` ```python binning_table.build() ``` -------------------------------- ### Initialize Categorical OptimalBinningSketch Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_sketch_binary.ipynb Instantiate an OptimalBinningSketch for a categorical variable with specific solver and cutoff settings. ```python variable_cat = "NAME_INCOME_TYPE" optbsketch = OptimalBinningSketch(name=variable_cat, dtype="categorical", solver="mip", min_bin_size=0.05, cat_cutoff=0.1) ``` -------------------------------- ### Initialize 2D Optimal Binning with Monotonic Trends Source: https://github.com/guillermo-navas-palencia/optbinning/blob/master/doc/source/tutorials/tutorial_binning_2d.ipynb Initialize OptimalBinning2D with specified monotonic trends for x and y axes and a minimum bin size. This is useful when you need to ensure that the event rate or WoE follows a specific trend across bins. ```python optb = OptimalBinning2D(name_x=variable1, name_y=variable2, monotonic_trend_x="descending", monotonic_trend_y="descending", min_bin_size=0.025) ```