SMOTEBaggingClassifier
- class imbalanced_ensemble.ensemble.SMOTEBaggingClassifier(base_estimator=None, n_estimators: int = 50, *, k_neighbors: int = 5, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=None, random_state=None, verbose=0)
A Bagging classifier with intergrated SMOTE over-sampling.
This implementation of SMOTEBagging [1] is similar to the scikit-learn implementation. It includes an additional step to balance the training set at fit time using a SMOTE over-sampler.
This implementation extends SMOTEBagging to support multi-class classification.
- Parameters
- base_estimatorobject, default=None
The base estimator to fit on oversampled dataset. If None, then the base estimator is a
Pipeline([SMOTE(), DecisionTreeClassifier()])
.- n_estimatorsint, default=50
The number of base estimators in the ensemble.
- k_neighborsint or object, default=5
If
int
, number of nearest neighbours to used to construct synthetic samples in SMOTE. If object, an estimator that inherits fromKNeighborsMixin
that will be used to find the k_neighbors.- max_samplesint or float, default=1.0
The number of samples to draw from X to train each base estimator (with replacement by default, see bootstrap for more details).
If
int
, then draw max_samples samples.If
float
, then draw max_samples * X.shape[0] samples.
- max_featuresint or float, default=1.0
The number of features to draw from X to train each base estimator ( without replacement by default, see bootstrap_features for more details).
If
int
, then draw max_features features.If
float
, then draw max_features * X.shape[1] features.
- bootstrapbool, default=True
Whether samples are drawn with replacement. If False, sampling without replacement is performed.
- bootstrap_featuresbool, default=False
Whether features are drawn with replacement.
- oob_scorebool, default=False
Whether to use out-of-bag samples to estimate the generalization error.
- warm_startbool, default=False
When set to True, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new ensemble. See Glossary for more details.
- n_jobsint, default=None
The number of jobs to run in parallel for both
fit()
andpredict()
.None
means 1 unless in ajoblib.parallel_backend
context.-1
means using all processors. See Glossary for more details.- random_stateint, RandomState instance or None, default=None
Control the randomization of the algorithm. Within each iteration, a different seed is generated for each sampler. If the base estimator accepts a random_state attribute, a different seed is generated for each instance in the ensemble. Pass an
int
for reproducible output across multiple function calls.If
int
,random_state
is the seed used by the random number generator;If
RandomState
instance, random_state is the random number generator;If
None
, the random number generator is theRandomState
instance used bynp.random
.
- verboseint, default=0
Controls the verbosity when fitting and predicting.
- Attributes
- base_estimator_pipeline estimator
The base estimator from which the ensemble is grown.
- base_sampler_SMOTE
The base sampler.
- estimators_list of classifiers
The collection of fitted sub-estimators.
- n_features_in_int
The number of features when
fit()
is performed.- estimators_list of estimators
The collection of fitted base estimators.
estimators_samples_
list of arraysThe subset of drawn samples for each base estimator.
- estimators_features_list of arrays
The subset of drawn features for each base estimator.
- estimators_n_training_samples_list of ints
The number of training samples for each fitted base estimators.
- classes_ndarray of shape (n_classes,)
The classes labels.
- n_classes_int or list
The number of classes.
- oob_score_float
Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when
oob_score
is True.- oob_decision_function_ndarray of shape (n_samples, n_classes)
Decision function computed with out-of-bag estimate on the training set. If n_estimators is small it might be possible that a data point was never left out during the bootstrap. In this case, oob_decision_function_ might contain NaN. This attribute exists only when
oob_score
is True.
See also
OverBaggingClassifier
Bagging with intergrated random over-sampling.
SMOTEBoostClassifier
SMOTE over-sampling integrated in AdaBoost.
UnderBaggingClassifier
Bagging with intergrated random under-sampling.
References
- 1
S. Wang, and X. Yao. “Diversity analysis on imbalanced data sets by using ensemble models.” 2009 IEEE symposium on computational intelligence and data mining. IEEE, 2009.
Examples
>>> from imbalanced_ensemble.ensemble import SMOTEBaggingClassifier >>> from sklearn.datasets import make_classification >>> >>> X, y = make_classification(n_samples=1000, n_classes=3, ... n_informative=4, weights=[0.2, 0.3, 0.5], ... random_state=0) >>> clf = SMOTEBaggingClassifier(random_state=0) >>> clf.fit(X, y) SMOTEBaggingClassifier(...) >>> clf.predict(X) array([...])
Methods
Average of the decision functions of the base classifiers.
fit
(X, y, *[, sample_weight, max_samples, ...])Build a SMOTEBagging ensemble of estimators from the training set (X, y).
get_params
([deep])Get parameters for this estimator.
predict
(X)Predict class for X.
Predict class log-probabilities for X.
Predict class probabilities for X.
score
(X, y[, sample_weight])Return the mean accuracy on the given test data and labels.
set_params
(**params)Predict class probabilities for X.
- decision_function(X)
Average of the decision functions of the base classifiers.
- Parameters
- X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
- Returns
- scorendarray of shape (n_samples, k)
The decision function of the input samples. The columns correspond to the classes in sorted order, as they appear in the attribute
classes_
. Regression and binary classification are special cases withk == 1
, otherwisek==n_classes
.
- property estimators_samples_
The subset of drawn samples for each base estimator.
Returns a dynamically generated list of indices identifying the samples used for fitting each member of the ensemble, i.e., the in-bag samples.
Note: the list is re-created at each call to the property in order to reduce the object memory footprint by not storing the sampling data. Thus fetching the property may be slower than expected.
- fit(X, y, *, sample_weight=None, max_samples=None, eval_datasets: dict = None, eval_metrics: dict = None, train_verbose: bool = False)
Build a SMOTEBagging ensemble of estimators from the training set (X, y).
- Parameters
- X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
- yarray-like of shape (n_samples,)
The target values (class labels in classification, real numbers in regression).
- sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, then samples are equally weighted. Note that this is supported only if the base estimator supports sample weighting.
- max_samplesint or float, default=None
Argument to use instead of self.max_samples.
- eval_datasetsdict, default=None
Dataset(s) used for evaluation during the ensemble training process. The keys should be strings corresponding to evaluation datasets’ names. The values should be tuples corresponding to the input samples and target values.
Example:
eval_datasets = {'valid' : (X_valid, y_valid)}
- eval_metricsdict, default=None
Metric(s) used for evaluation during the ensemble training process.
If
None
, use 3 default metrics:'acc'
:sklearn.metrics.accuracy_score()
'balanced_acc'
:sklearn.metrics.balanced_accuracy_score()
'weighted_f1'
:sklearn.metrics.f1_score(average='weighted')
If
dict
, the keys should be strings corresponding to evaluation metrics’ names. The values should be tuples corresponding to the metric function (callable
) and additional kwargs (dict
).The metric function should at least take 2 named/keyword arguments,
y_true
and one of [y_pred
,y_score
], and returns a float as the evaluation score. Keyword arguments:y_true
, 1d-array of shape (n_samples,), true labels or binary label indicators corresponds to ground truth (correct) labels.When using
y_pred
, input will be 1d-array of shape (n_samples,) corresponds to predicted labels, as returned by a classifier.When using
y_score
, input will be 2d-array of shape (n_samples, n_classes,) corresponds to probability estimates provided by the predict_proba method. In addition, the order of the class scores must correspond to the order oflabels
, if provided in the metric function, or else to the numerical or lexicographical order of the labels iny_true
.
The metric additional kwargs should be a dictionary that specifies the additional arguments that need to be passed into the metric function.
Example:
{'weighted_f1': (sklearn.metrics.f1_score, {'average': 'weighted'})}
- train_verbosebool, default=False
Controls the verbosity during ensemble training/fitting.
False
: disable training verbose.True
: print the performance score to sys.stdout after the parallel training finished.
- Returns
- selfobject
- get_params(deep=True)
Get parameters for this estimator.
- Parameters
- deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators.
- Returns
- paramsdict
Parameter names mapped to their values.
- property n_features_
DEPRECATED: Attribute n_features_ was deprecated in version 1.0 and will be removed in 1.2. Use n_features_in_ instead.
- predict(X)
Predict class for X.
The predicted class of an input sample is computed as the class with the highest mean predicted probability. If base estimators do not implement a
predict_proba
method, then it resorts to voting.- Parameters
- X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
- Returns
- yndarray of shape (n_samples,)
The predicted classes.
- predict_log_proba(X)
Predict class log-probabilities for X.
The predicted class log-probabilities of an input sample is computed as the log of the mean predicted class probabilities of the base estimators in the ensemble.
- Parameters
- X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
- Returns
- pndarray of shape (n_samples, n_classes)
The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
- predict_proba(X)
Predict class probabilities for X.
The predicted class probabilities of an input sample is computed as the mean predicted class probabilities of the base estimators in the ensemble. If base estimators do not implement a
predict_proba
method, then it resorts to voting and the predicted class probabilities of an input sample represents the proportion of estimators predicting each class.- Parameters
- X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
- Returns
- pndarray of shape (n_samples, n_classes)
The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
- score(X, y, sample_weight=None)
Return the mean accuracy on the given test data and labels.
In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.
- Parameters
- Xarray-like of shape (n_samples, n_features)
Test samples.
- yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True labels for X.
- sample_weightarray-like of shape (n_samples,), default=None
Sample weights.
- Returns
- scorefloat
Mean accuracy of
self.predict(X)
wrt. y.
- set_params(**params)
Predict class probabilities for X.
The predicted class probabilities of an input sample is computed as the mean predicted class probabilities of the base estimators in the ensemble. If base estimators do not implement a
predict_proba
method, then it resorts to voting and the predicted class probabilities of an input sample represents the proportion of estimators predicting each class.- Parameters
- X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
- Returns
- pndarray of shape (n_samples, n_classes)
The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.