OptBinning Documentation

repository·master·Indexed 17 days ago

https://github.com/guillermo-navas-palencia/optbinning

A 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.

Tokens
21.3K
Snippets
70
Records
90
Agent score
68%

What's inside OptBinning

  1. Overview of OptBinning

    master
    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.
  2. Explore OptBinning tutorials by category

    master

    OptBinning 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-learn pipelines, 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.
  3. Compare monotonicity trend options

    master

    When binning variables that exhibit a monotonicity trend (peak or valley), you can choose between two monotonic_trend options 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.
  4. Use OptimalBinningSketch for scalable binning in streaming settings

    master
    The OptimalBinningSketch class 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.
  5. Perform distributed optimal binning using PySpark and OptimalBinningSketch

    master

    You can compute the optimal binning of a variable from a large dataset in a distributed fashion using PySpark's mapPartitions and treeReduce methods combined with OptimalBinningSketch.

    To implement this MapReduce pattern:

    1. Partition the data: Use df.repartition(n) to split your dataset into multiple partitions.
    2. Map Phase: Use mapPartitions to create an OptimalBinningSketch instance for each partition. Inside the partition function, convert the partition to a Pandas DataFrame, initialize OptimalBinningSketch(eps=...), and call .add(x, y) where x is the feature and y is the target.
    3. Reduce Phase: Use treeReduce with a merge function that calls optbsketch.merge(other_optbsketch) to aggregate the sketches from all partitions into a single global sketch.

    Note: Ensure spark.sql.execution.arrow.enabled is set to true for 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)
  6. Install OptBinning

    master

    You 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]
  7. Analyze the Expected Value of Perfect Information (EVPI) and Value of Stochastic Solution (VSS)

    master

    In 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:

    1. 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 (where SIV is the Stochastic Information Value).
    2. 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) (where EVS_scenario_i is the IV of the expected value solution applied to scenario i).
  8. Perform distributed or batch binning with merge()

    master

    The OptimalBinningSketch supports 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()
  9. Enforce monotonic trends in piecewise binning

    master

    You can force the event rate curve to follow a specific trend using the monotonic_trend parameter. 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, or valley) that maximizes Information Value.
    • Specific trends: You can explicitly set trends like convex or concave.

    To use auto, you must provide an estimator (e.g., from sklearn) to the OptimalPWBinning constructor.

    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)