OptBinning Documentation
repository·master·Indexed 17 days ago
https://github.com/guillermo-navas-palencia/optbinningA Python library for the optimal discretization of variables into bins using mathematical programming formulations. It supports binary, continuous, and multiclass target types for feature engineering and scorecard modeling. Key features include 2D binning, stochastic optimal binning (SBOptimalBinning), scalable streaming binning via OptimalBinningSketch, and the MDLP discretization algorithm. The library also provides utilities for Weight of Evidence (WoE) transformations, Gini coefficient calculation, and counterfactual explanations.
What's inside OptBinning
- OptBinning is a Python library designed for the optimal discretization of variables into bins. It uses a rigorous mathematical programming formulation to solve the optimal binning problem for various target types, including binary, continuous, and multiclass targets. The library allows for the incorporation of specific constraints during the binning process.
Explore OptBinning tutorials by category
masterOptBinning provides a comprehensive set of tutorials categorized by use case, ranging from basic to advanced levels. You can find specialized guidance for:
- Optimal Binning: Tutorials for binary, continuous, and multiclass target types, including large-scale and local solver approaches.
- Binning Process: Integration with
scikit-learnpipelines, FICO xAI workflows, and update binning processes. - Scorecard Development: Building scorecards for binary or continuous targets, monitoring scorecards, and counterfactual analysis.
- Optimal Piecewise Binning: Specialized tutorials for piecewise binary and continuous binning.
- Batch and Streaming Data: Using sketching techniques for binary targets, including PySpark support.
- Uncertainty: Handling optimal binning under uncertainty.
- 2D Binning: Tutorials for 2D binning with both binary and continuous targets.
Compare monotonicity trend options
masterWhen binning variables that exhibit a monotonicity trend (peak or valley), you can choose between two
monotonic_trendoptions to balance speed and Information Value (IV):monotonic_trend="auto": The default approach. It aims for a more optimal solution but may take more CPU time.monotonic_trend="auto_heuristic": A faster approach that uses a heuristic. It can reduce CPU time by approximately 25% while typically losing less than 1% in IV. This is particularly useful for large-scale datasets where the number of bins is high.
Use OptimalBinningSketch for scalable binning in streaming settings
masterTheOptimalBinningSketchclass provides a scalable, memory-efficient, and robust algorithm for performing optimal binning on streaming data. It is designed for constrained discretization of numerical features given a binary target, aiming to maximize statistics like Jeffrey's divergence or Gini. This is particularly useful when data is too large to fit in memory or arrives in a stream, where traditional binning algorithms might fail due to lack of support for streaming constraints.Install OptBinning via pip
masterTo install the current stable release of OptBinning, use the standard
pippackage manager.pip install optbinningPerform distributed optimal binning using PySpark and OptimalBinningSketch
masterYou can compute the optimal binning of a variable from a large dataset in a distributed fashion using PySpark's
mapPartitionsandtreeReducemethods combined withOptimalBinningSketch.To implement this MapReduce pattern:
- Partition the data: Use
df.repartition(n)to split your dataset into multiple partitions. - Map Phase: Use
mapPartitionsto create anOptimalBinningSketchinstance for each partition. Inside the partition function, convert the partition to a Pandas DataFrame, initializeOptimalBinningSketch(eps=...), and call.add(x, y)wherexis the feature andyis the target. - Reduce Phase: Use
treeReducewith a merge function that callsoptbsketch.merge(other_optbsketch)to aggregate the sketches from all partitions into a single global sketch.
Note: Ensure
spark.sql.execution.arrow.enabledis set totruefor efficient data transfer between Spark and Pandas.from pyspark.sql import SparkSession import pandas as pd from optbinning import OptimalBinningSketch # Setup Spark spark = SparkSession.builder.getOrCreate() spark.conf.set("spark.sql.execution.arrow.enabled", "true") # Load and repartition data df = spark.read.csv("data/kaggle/HomeCreditDefaultRisk/application_train.csv", sep=",", header=True, inferSchema=True) n_partitions = 4 df = df.repartition(n_partitions) # Define variables variable = "EXT_SOURCE_3" target = "TARGET" columns = [variable, target] # Map function: creates a sketch per partition def add(partition): df_pandas = pd.DataFrame.from_records(partition, columns=columns) x = df_pandas[variable] y = df_pandas[target] optbsketch = OptimalBinningSketch(eps=0.001) optbsketch.add(x, y) return [optbsketch] # Merge function: aggregates sketches def merge(optbsketch, other_optbsketch): optbsketch.merge(other_optbsketch) return optbsketch # Execute distributed computation optbsketch = df.select(columns).rdd.mapPartitions(lambda partition: add(partition)).treeReduce(merge)- Partition the data: Use
Install OptBinning from source
masterTo install the latest development version from the git repository, clone the repository and run the installation script from the root directory.
# Clone the repository git clone https://github.com/guillermo-navas-palencia/optbinning # Install from source cd optbinning python setup.py installInstall OptBinning
masterYou can install the standard release of OptBinning from PyPI using
pip.Depending on your requirements, you can also install optional extras for distributed/stream binning or specific solver support.
# Standard installation pip install optbinning # Installation with batch and stream binning algorithms pip install optbinning[distributed] # Installation with support for the ecos solver pip install optbinning[ecos]Install a specific OptBinning release
masterIf you need a specific version of OptBinning, you can download it from the official GitHub releases page and install it using the
setup.pyscript.# Download from https://github.com/guillermo-navas-palencia/optbinning/releases python setup.py installAnalyze the Expected Value of Perfect Information (EVPI) and Value of Stochastic Solution (VSS)
masterIn the context of stochastic optimal binning, you can quantify the benefits of using a stochastic model versus a standard expected value approach using two metrics:
Expected Value of Perfect Information (EVPI): The difference between the average Information Value (IV) obtained if you knew which scenario would occur in advance, and the IV obtained from the stochastic model.
EVPI = Average(IV_scenario_i) - SIV(whereSIVis the Stochastic Information Value).
Value of Stochastic Solution (VSS): The gain in IV achieved by using the stochastic model instead of applying the 'Expected Value Solution' (the solution derived from the average scenario) to each individual scenario.
VSS = SIV - Average(EVS_scenario_i)(whereEVS_scenario_iis the IV of the expected value solution applied to scenarioi).
Perform distributed or batch binning with merge()
masterThe
OptimalBinningSketchsupports a map-reduce pattern for processing large datasets distributed across different files or nodes. You can create multiple sketch objects for different data partitions and then merge them into a single global sketch using the.merge(other_optbsketch)method.This approach is ideal for:
- Distributed infrastructure: Processing data without centralizing it.
- Large datasets: Handling data that exceeds memory capacity.
- Federated learning: Merging sketches sent from different devices to a central cloud.
from functools import reduce def add_partition(filepath): df = pd.read_parquet(path=filepath, columns=[variable, target]) x = df[variable].values y = df[target].values optbsketch = OptimalBinningSketch(name=variable, dtype="numerical", sketch="gk", min_bin_size=0.05) optbsketch.add(x, y) return optbsketch def merge_sketches(optbsketch, other_optbsketch): optbsketch.merge(other_optbsketch) return optbsketch # Map-reduce pattern filepaths = ["data/df1.parquet.gzip", "data/df2.parquet.gzip", "data/df3.parquet.gzip"] optbsketch = reduce(merge_sketches, map(add_partition, filepaths)) optbsketch.solve()Enforce monotonic trends in piecewise binning
masterYou can force the event rate curve to follow a specific trend using the
monotonic_trendparameter. This is useful when business constraints require a specific relationship between the feature and the target.auto(default): Uses a machine-learning-based classifier (e.g.,GradientBoostingClassifier) to choose the trend (ascending,descending,peak, orvalley) that maximizes Information Value.- Specific trends: You can explicitly set trends like
convexorconcave.
To use
auto, you must provide anestimator(e.g., fromsklearn) to theOptimalPWBinningconstructor.from sklearn.ensemble import GradientBoostingClassifier # Force a convex trend using a Gradient Boosting estimator optb = OptimalPWBinning(name=variable, estimator=GradientBoostingClassifier(), monotonic_trend="convex") optb.fit(x, y)