SingletonBinning
- class binlearn.methods.SingletonBinning(preserve_dataframe: bool | None = None, fit_jointly: bool | None = None, *, bin_spec: Any | None = None, bin_representatives: Any | None = None, class_: str | None = None, module_: str | None = None)[source]
Bases:
FlexibleBinningBaseSingleton binning implementation using clean architecture.
Creates one bin for each unique value in the numeric data. This method preserves all distinct values by creating individual bins for each unique data point, making it ideal for discrete numeric variables or cases where no information loss is acceptable.
Each unique numeric value becomes both a bin definition and its own representative. This creates a one-to-one mapping between unique values in the data and bin definitions, effectively implementing an identity transformation for unique values.
The method only supports numeric data and automatically filters out NaN and infinite values during bin creation. When all values are invalid (NaN/inf), it falls back to creating a single default bin to maintain functionality.
This is particularly useful for: - Discrete numeric variables (e.g., counts, ratings, categories encoded as numbers) - Preserving exact values in downstream processing - Creating lookup tables for categorical encoding - Cases where data aggregation is not desired
This implementation follows the clean binlearn architecture with straight inheritance, dynamic column resolution, and parameter reconstruction capabilities.
- Parameters:
preserve_dataframe – Whether to preserve pandas DataFrame structure in transform operations. If None, uses configuration default.
fit_jointly – Whether to fit all columns together (True) or independently (False). For singleton binning, this typically doesn’t affect results since each unique value gets its own bin regardless. If None, uses configuration default.
bin_spec – Pre-computed flexible bin specification for reconstruction. Internal use only - should not be provided during normal initialization.
bin_representatives – Pre-computed representatives dictionary for reconstruction. Internal use only.
class – Class name for reconstruction compatibility. Internal use only.
module – Module name for reconstruction compatibility. Internal use only.
Example
>>> import numpy as np >>> from binlearn.methods import SingletonBinning >>> >>> # Create discrete numeric data >>> data = np.array([1, 2, 2, 3, 3, 3, 4, 5, 5]).reshape(-1, 1) >>> >>> # Initialize singleton binning >>> binner = SingletonBinning() >>> >>> # Fit and transform >>> binner.fit(data) >>> data_binned = binner.transform(data) >>> >>> # Check unique bins created >>> print(f"Original unique values: {np.unique(data)}") >>> print(f"Bin specifications: {binner.bin_spec_[0]}") >>> print(f"Number of bins: {len(binner.bin_spec_[0])}") >>> >>> # Verify identity mapping >>> for i, unique_val in enumerate(np.unique(data)): ... assert binner.bin_spec_[0][i] == unique_val ... assert binner.bin_representatives_[0][i] == unique_val
Note
Creates exactly as many bins as there are unique values in the data
Only processes finite numeric values (filters out NaN and infinite values)
Representatives are identical to the bin definitions (unique values)
Preserves all information from original discrete numeric data
Falls back gracefully when all data is invalid (creates single default bin)
Does not require guidance data (unsupervised method)
Each column is processed independently
See also
ManualFlexibleBinning: User-defined flexible bin specifications EqualWidthBinning: Fixed-width interval binning for continuous data EqualFrequencyBinning: Equal-frequency interval binning
- __init__(preserve_dataframe: bool | None = None, fit_jointly: bool | None = None, *, bin_spec: Any | None = None, bin_representatives: Any | None = None, class_: str | None = None, module_: str | None = None)[source]
Initialize singleton binning with basic configuration options.
Sets up singleton binning that creates one bin per unique value. This method has minimal configuration since its behavior is deterministic - each unique value gets its own bin.
- Parameters:
preserve_dataframe – Whether to preserve pandas DataFrame structure in transform operations. If None, uses configuration default.
fit_jointly – Whether to fit all columns together (True) or independently (False). For singleton binning, this typically doesn’t change the result since each unique value gets its own bin regardless of other columns. If None, uses configuration default.
bin_spec – Pre-computed flexible bin specification dictionary for reconstruction. Maps column identifiers to lists of unique values. Internal use only - should not be provided during normal initialization.
bin_representatives – Pre-computed representatives dictionary for reconstruction. For singleton binning, this is identical to bin_spec. Internal use only.
class – Class name string for reconstruction compatibility. Internal use only.
module – Module name string for reconstruction compatibility. Internal use only.
Example
>>> # Standard initialization with default settings >>> binner = SingletonBinning() >>> >>> # Preserve DataFrame structure >>> binner = SingletonBinning(preserve_dataframe=True) >>> >>> # Fit all columns together (though doesn't affect singleton results) >>> binner = SingletonBinning(fit_jointly=True, preserve_dataframe=True)
Note
Minimal configuration needed since behavior is deterministic
Configuration defaults are applied for None parameters
fit_jointly parameter exists for consistency but doesn’t change results
Reconstruction parameters (bin_spec, bin_representatives, class_, module_) are used internally for object reconstruction and should not be provided during normal usage
No guidance_columns parameter since this is an unsupervised method
- classmethod __init_subclass__(**kwargs)
Set the
set_{method}_requestmethods.This uses PEP-487 [1] to set the
set_{method}_requestmethods. It looks for the information available in the set default values which are set using__metadata_request__*class attributes, or inferred from method signatures.The
__metadata_request__*class attributes are used when a method does not explicitly accept a metadata through its arguments or if the developer would like to specify a request value for those metadata which are different from the defaultNone.References
- static check_data_quality(data: ndarray[Any, Any], name: str = 'data') None
Check data quality and issue warnings if needed.
- fit(X: Any, y: Any | None = None, **fit_params: Any) GeneralBinningBase
Fit the binning transformer with comprehensive orchestration.
This method orchestrates the complete fitting process, handling parameter validation, input preprocessing, column separation, and routing to the appropriate fitting strategy (joint vs independent).
- Parameters:
X – Input data to fit the binning transformer on. Can be: - pandas.DataFrame: Column names are preserved - polars.DataFrame: Column names are preserved - numpy.ndarray: Numeric column indices are used - array-like: Converted to numpy array
y – Target values for supervised binning methods. Ignored by unsupervised methods. Can be array-like or None.
**fit_params – Additional fitting parameters passed to the specific binning algorithm implementation. Common parameters include: - guidance_data: Alternative guidance data (conflicts with fit_jointly=True)
- Returns:
The fitted binning transformer instance.
- Return type:
self
- Raises:
ValueError – If parameter validation fails, inputs are invalid, or conflicting parameters are provided (e.g., fit_jointly=True with guidance_data).
BinningError – If the binning algorithm fails to fit the data.
RuntimeError – If an unexpected error occurs during fitting.
Example
>>> from binlearn import EqualWidthBinning >>> import pandas as pd >>> X = pd.DataFrame({'feature1': [1, 2, 3, 4, 5], 'feature2': [10, 20, 30, 40, 50]}) >>> binner = EqualWidthBinning(n_bins=3) >>> binner.fit(X) EqualWidthBinning(...)
Note
The method automatically handles column separation when guidance_columns is specified, routing guidance columns separately from binning columns. The fitting strategy (joint vs independent) is determined by the fit_jointly parameter.
- fit_transform(X, y=None, **fit_params)
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
- Parameters:
X (array-like of shape (n_samples, n_features)) – Input samples.
y (array-like of shape (n_samples,) or (n_samples, n_outputs), default=None) – Target values (None for unsupervised transformations).
**fit_params (dict) – Additional fit parameters.
- Returns:
X_new – Transformed array.
- Return type:
ndarray array of shape (n_samples, n_features_new)
- get_input_columns() list[Any] | None
Get input columns for data preparation.
This method should be overridden by derived classes to provide appropriate column information without exposing binning-specific concepts.
- Returns:
Column information or None if not available
- 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: bool = True) dict[str, Any]
Get parameters for this estimator, including fitted parameters.
This method extends sklearn’s standard get_params to include fitted parameters when the estimator is fitted, enabling complete object reconstruction through the get_params/set_params interface. This is essential for pipeline persistence and model serialization.
- Parameters:
deep – If True, returns parameters for sub-estimators (not applicable here but maintained for sklearn compatibility).
- Returns:
- Return type:
Dictionary of parameter names mapped to their values, including
Example
>>> binner = EqualWidthBinning(n_bins=5) >>> params = binner.get_params() >>> print(params) {'n_bins': 5, 'clip': None, ..., 'class_': 'EqualWidthBinning', 'module_': '...'} >>> >>> binner.fit(X) >>> fitted_params = binner.get_params() >>> # Now includes: {'bin_edges': {...}, 'bin_representatives': {...}, ...}
Note
Automatically extracts constructor parameters from __init__ signature
Includes fitted parameters only when estimator is fitted
Adds class metadata for reconstruction workflows
Excludes internal sklearn attributes like n_features_in_
class_ and module_ parameters are handled specially during set_params
- inverse_transform(X: Any) Any
Inverse transform from bin indices back to representative values.
Converts discrete bin indices back to their representative values, effectively reversing the binning transformation. This is useful for interpreting results or reconstructing approximate original values.
- Parameters:
X – Input data containing bin indices to inverse transform. Should contain only binning columns (no guidance columns). Can be: - pandas.DataFrame: Column names should match binning columns - polars.DataFrame: Column names should match binning columns - numpy.ndarray: Must have same number of binning columns - array-like: Converted to numpy array
- Returns:
Inverse transformed data where bin indices are replaced with their representative values (typically bin centers). Output format matches the preserve_dataframe setting.
- Raises:
RuntimeError – If the transformer has not been fitted yet.
ValueError – If input data has wrong number of columns or invalid format.
BinningError – If inverse transformation fails.
Example
>>> # After fitting and transforming >>> X_binned = [[0, 1], [1, 0], [2, 2]] # Bin indices >>> X_reconstructed = binner.inverse_transform(X_binned) >>> print(X_reconstructed) [[0.5, 1.5], [1.5, 0.5], [2.5, 2.5]] # Representative values
Note
For guided binning (when guidance_columns is specified), the input should only contain the binning columns, not the guidance columns. The number of input columns must match the number of binning columns.
- set_output(*, transform=None)
Set output container.
See Introducing the set_output API 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: Any) SklearnIntegrationBase
Set the parameters of this estimator.
This method supports reconstruction workflows by handling fitted parameters that come from get_params() output (without underscores) and setting them as fitted attributes (with underscores).
- Parameters:
**params – Parameters to set. Can include: - Regular constructor parameters (n_bins, clip, etc.) - Fitted parameters from get_params (bin_edges, bin_representatives) - Class metadata (ignored during reconstruction)
- Returns:
Returns the instance itself.
- Return type:
self
- transform(X: Any) Any
Transform input data using fitted binning parameters.
Applies the fitted binning transformation to new data, converting continuous values to discrete bin indices or representatives. Handles column separation when guidance columns are present.
- Parameters:
X – Input data to transform. Must have the same structure as the data used during fitting (same number of columns). Can be: - pandas.DataFrame: Column names should match training data - polars.DataFrame: Column names should match training data - numpy.ndarray: Must have same number of columns as training - array-like: Converted to numpy array
- Returns:
Transformed data where continuous values are replaced with bin indices or representative values. The output format depends on: - preserve_dataframe setting: DataFrame vs array format - binning method: indices vs representatives - guidance_columns: only binning columns are transformed
- Raises:
RuntimeError – If the transformer has not been fitted yet.
ValueError – If the input data has incompatible structure or format.
BinningError – If transformation fails due to data issues.
Example
>>> # After fitting >>> X_new = pd.DataFrame({'feature1': [1.5, 2.5], 'feature2': [15, 25]}) >>> X_binned = binner.transform(X_new) >>> print(X_binned) [[0, 0], [1, 1]] # Bin indices
Note
When guidance_columns is specified, only the binning columns are transformed. Guidance columns are filtered out from the output. The method preserves the original data format when preserve_dataframe=True.
- static validate_array_like(data: Any, name: str = 'data', allow_none: bool = False) ndarray[Any, Any] | None
Validate and convert array-like input to numpy array.
This method provides robust validation and conversion of various input formats to numpy arrays, with comprehensive error handling and helpful suggestions for common issues.
- Parameters:
data – Input data to validate and convert. Can be: - numpy.ndarray: Used directly - pandas.DataFrame/Series: Converted to numpy array - polars.DataFrame: Converted to numpy array - list, tuple: Converted to numpy array - None: Allowed only if allow_none=True
name – Name of the data parameter for error messages. Used to provide context in error messages (e.g., “X”, “y”, “guidance_data”).
allow_none – Whether to allow None as a valid input. If True, None is returned unchanged; if False, None raises InvalidDataError.
- Returns:
Validated numpy array, or None if data is None and allow_none=True. The returned array maintains the same data content but is guaranteed to be a numpy array.
- Raises:
InvalidDataError – If validation fails: - data is None when allow_none=False - data cannot be converted to numpy array - Conversion process encounters errors
Example
>>> # Valid inputs >>> arr = ValidationMixin.validate_array_like([1, 2, 3], "X") >>> print(type(arr)) <class 'numpy.ndarray'> >>> >>> # Allow None >>> result = ValidationMixin.validate_array_like(None, "y", allow_none=True) >>> print(result) None >>> >>> # Invalid input >>> ValidationMixin.validate_array_like(None, "X", allow_none=False) InvalidDataError: X cannot be None
Note
This method focuses on format validation and conversion. Content validation (like checking for NaN values) should be done separately using other validation methods.
Examples
Basic Categorical Encoding
import pandas as pd
import numpy as np
from binlearn.methods import SingletonBinning
# Create categorical data
categorical_data = pd.DataFrame({
'category': ['A', 'B', 'A', 'C', 'B', 'A', 'D'],
'rating': ['good', 'bad', 'good', 'excellent', 'bad', 'good', 'fair']
})
# Apply singleton binning
singleton_binner = SingletonBinning(preserve_dataframe=True)
categorical_binned = singleton_binner.fit_transform(categorical_data)
print(f"Original shape: {categorical_data.shape}")
print(f"Binned shape: {categorical_binned.shape}")
print(f"Original categories: {categorical_data['category'].unique()}")
Mixed Data Types
# Mixed categorical and numerical data
mixed_data = pd.DataFrame({
'category': ['A', 'B', 'A', 'C', 'B'],
'numerical': [1.5, 2.3, 1.5, 4.1, 2.3],
'rating': ['high', 'low', 'high', 'medium', 'low']
})
# SingletonBinning works on all data types
binner = SingletonBinning(preserve_dataframe=True)
mixed_binned = binner.fit_transform(mixed_data)
With Custom Representatives
# Using custom bin representatives
from binlearn.utils.types import BinRepsDict
custom_reps: BinRepsDict = {
'category': {0: 'Type_A', 1: 'Type_B', 2: 'Type_C'},
'rating': {0: 'Poor', 1: 'Good', 2: 'Excellent'}
}
binner = SingletonBinning(
bin_representatives=custom_reps,
preserve_dataframe=True
)
# Note: You still need to provide bin_edges for custom representatives
# This is typically used when you have pre-trained binning parameters