binlearn.methods.EqualFrequencyBinning

class binlearn.methods.EqualFrequencyBinning(n_bins: int | str | None = None, quantile_range: tuple[float, float] | None = None, clip: bool | None = None, preserve_dataframe: bool | None = None, fit_jointly: bool | None = None, *, bin_edges: dict[Any, list[float]] | None = None, bin_representatives: dict[Any, list[float]] | None = None, class_: str | None = None, module_: str | None = None)[source]

Equal frequency binning implementation for creating balanced population bins.

This class implements equal frequency binning (also known as quantile binning), which creates bins containing approximately equal numbers of observations. Unlike equal width binning that creates uniform intervals, equal frequency binning adapts bin boundaries to the data distribution, ensuring each bin has roughly the same number of data points.

Equal frequency binning is particularly effective for: - Skewed distributions where equal width bins would create imbalanced populations - Creating bins with consistent statistical power for analysis - Preprocessing for algorithms that perform better with balanced bin sizes - Ordinal discretization that preserves ranking relationships

Key Features: - Creates bins with approximately equal observation counts - Handles duplicate values intelligently by adjusting bin boundaries - Supports custom quantile ranges for focusing on specific data portions - Automatic handling of edge cases (insufficient unique values, duplicates) - Inherits all interval binning capabilities (clipping, format preservation, etc.)

Algorithm: 1. Sort the data values for each column 2. Calculate quantile positions for n_bins equal-frequency intervals 3. Find actual data values at or near these quantile positions 4. Adjust bin boundaries to handle duplicate values properly 5. Create representative values (typically quantile midpoints)

Parameters:
  • n_bins – Number of bins to create, or string specification like ‘sqrt’, ‘log2’. Can be an integer for exact count or string for automatic calculation. Default value can be configured globally via binlearn.config.

  • quantile_range – Optional (min_quantile, max_quantile) tuple to focus binning on a specific portion of the data distribution. For example, (0.1, 0.9) creates bins only within the 10th-90th percentile range, ignoring outliers.

bin_edges_

Dictionary mapping column identifiers to lists of bin edges after fitting. Edges correspond to quantile boundaries in the data.

bin_representatives_

Dictionary mapping column identifiers to lists of bin representatives (typically quantile midpoints).

Example

>>> import numpy as np
>>> from binlearn.methods import EqualFrequencyBinning
>>>
>>> # Skewed data - exponential distribution
>>> X = np.random.exponential(2, (1000, 1))
>>> binner = EqualFrequencyBinning(n_bins=4)
>>> binner.fit(X)
>>> X_binned = binner.transform(X)
>>> # Each bin contains approximately 250 observations
>>>
>>> # Focus on middle 80% of data, ignoring extreme outliers
>>> binner_focused = EqualFrequencyBinning(n_bins=5, quantile_range=(0.1, 0.9))
>>> binner_focused.fit(X)

Note

  • Works best with continuous numeric data having many unique values

  • May create fewer bins than requested if data has insufficient unique values

  • Duplicate values at quantile boundaries are handled by boundary adjustment

  • Consider the trade-off between bin count and meaningful bin boundaries

  • Inherits clipping behavior and DataFrame preservation from IntervalBinningBase

__init__(n_bins: int | str | None = None, quantile_range: tuple[float, float] | None = None, clip: bool | None = None, preserve_dataframe: bool | None = None, fit_jointly: bool | None = None, *, bin_edges: dict[Any, list[float]] | None = None, bin_representatives: dict[Any, list[float]] | None = None, class_: str | None = None, module_: str | None = None)[source]

Initialize equal frequency binning with configuration and parameters.

Sets up the equal frequency binning method with user-specified parameters and configuration defaults. The method integrates with binlearn’s global configuration system and supports flexible bin count specification.

Parameters:
  • n_bins – Number of equal-frequency bins to create, or string specification for automatic calculation. Can be: - Integer: exact number of bins to create - ‘sqrt’: number of bins = sqrt(n_samples) - ‘log2’: number of bins = log2(n_samples) - ‘sturges’: Sturges’ rule for histogram bins If None, uses global configuration default for ‘equal_frequency’ method.

  • quantile_range – Optional (min_quantile, max_quantile) tuple to focus binning on a specific portion of the data distribution. Values should be between 0.0 and 1.0 with min_quantile < max_quantile. For example, (0.05, 0.95) creates bins within the 5th-95th percentile range, effectively ignoring extreme outliers.

  • clip – Whether to clip out-of-range values to the nearest bin boundary during transformation. If True, values outside the range are assigned to the nearest edge bin. If False, they receive special out-of-range indices. If None, uses global configuration default.

  • preserve_dataframe – Whether to preserve DataFrame format in outputs when input is a DataFrame. If None, uses global configuration default.

  • fit_jointly – Whether to fit all columns together (not applicable for equal frequency binning as it’s inherently per-column). If None, uses global configuration default.

  • bin_edges – Pre-computed bin edges for reconstruction/deserialization. If provided, no fitting is performed and these edges are used directly. Should be a dictionary mapping column identifiers to lists of edge values.

  • bin_representatives – Pre-computed bin representatives for reconstruction. Must be provided together with bin_edges. Should be a dictionary mapping column identifiers to lists of representative values.

  • class – Class name for reconstruction compatibility (ignored during normal initialization).

  • module – Module name for reconstruction compatibility (ignored during normal initialization).

Example

>>> # Basic initialization with automatic bin count
>>> binner = EqualFrequencyBinning(n_bins='sqrt')
>>>
>>> # Fixed number of bins with outlier handling
>>> binner = EqualFrequencyBinning(n_bins=10, quantile_range=(0.1, 0.9))
>>>
>>> # Reconstruction from saved parameters
>>> binner = EqualFrequencyBinning(
...     n_bins=4,
...     bin_edges={'col1': [0.1, 0.3, 0.6, 0.8, 0.95]},
...     bin_representatives={'col1': [0.2, 0.45, 0.7, 0.875]}
... )

Note

  • String n_bins values are resolved during fitting based on data size

  • quantile_range is useful for handling outliers and focusing analysis

  • Pre-computed edges and representatives enable object reconstruction

  • Parameters integrate with binlearn’s global configuration system