ClassBalanceSampler filter.
Balance class distribution through resampling.
Classes
class preprocessing.sampling.class_balance.ClassBalanceSampler(ResamplingTransformer)
Balance class distribution through resampling.
Resamples instances to achieve balanced class distribution. Can oversample minority classes, undersample majority classes, or both.
Constructor
__init__( self, strategy: str = 'oversample', target_ratio: float = 1.0, random_state: Optional[int] = None, )
Parameters
strategy
str
= "oversample"
Balancing strategy:
- •"oversample": Duplicate minority class instances
- •"undersample": Remove majority class instances
- •"both": Combination (SMOTE-like without synthetic generation)
target_ratio
float
= 1.0
Target ratio of minority to majority class (1.0 = equal).
random_state
int
Random seed for reproducibility.
python
>>> import numpy as np
>>> from tuiml.preprocessing.sampling import ClassBalanceSampler
python
>>> # Imbalanced dataset: 90 class 0, 10 class 1
>>> X = np.arange(100).reshape(-1, 1)
>>> y = np.array([0]*90 + [1]*10)
python
>>> # Oversample minority class
>>> balancer = ClassBalanceSampler(strategy="oversample", random_state=42)
>>> X_bal, y_bal = balancer.fit_transform(X, y)
>>> Counter(y_bal)
Counter({0: 90, 1: 90})
python
>>> # Undersample majority class
>>> balancer = ClassBalanceSampler(strategy="undersample", random_state=42)
>>> X_bal, y_bal = balancer.fit_transform(X, y)
>>> Counter(y_bal)
Counter({0: 10, 1: 10})
Methods
get_parameter_schema
(cls)
fit
(self, X: np.ndarray, y: Optional[np.ndarray]=None) -> 'ClassBalanceSampler'
fit
(self, X: np.ndarray, y: Optional[np.ndarray]=None) -> 'ClassBalanceSampler'
Record the class distribution used to plan the resampling.
Parameters
X
np.ndarray of shape (n_samples, n_features)
Input data.
y
np.ndarray of shape (n_samples,)
Target values. Required, since the classes drive the balancing.
Returns
self
object
The fitted sampler.
transform
(self, X: np.ndarray, y: Optional[np.ndarray]=None) -> Tuple[np.ndarray, Optional[np.ndarray]]
transform
(self, X: np.ndarray, y: Optional[np.ndarray]=None) -> Tuple[np.ndarray, Optional[np.ndarray]]
Resample the data so the classes are balanced.
Parameters
X
np.ndarray of shape (n_samples, n_features)
Input data.
y
np.ndarray of shape (n_samples,)
Target values. Required, since the classes drive the balancing.
Returns
X_balanced
np.ndarray
Resampled feature matrix.
y_balanced
np.ndarray
Matching resampled targets. Row count differs from the input, so this transformer changes the number of samples.
__repr__
(self) -> str