EasyEnsembleClassifier

class imbalanced_ensemble.ensemble.EasyEnsembleClassifier(n_estimators: int = 50, *, base_estimator=None, 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)

Bag of balanced boosted learners also known as EasyEnsemble.

This algorithm is known as EasyEnsemble [1]. The classifier is an ensemble of AdaBoost learners trained on different balanced boostrap samples. The balancing is achieved by random under-sampling.

This implementation extends EasyEnsemble to support multi-class classification.

Parameters
n_estimatorsint, default=50

Number of AdaBoost learners in the ensemble.

base_estimatorestimator object, default=AdaBoostClassifier(n_estimators=10)

The base AdaBoost classifier used in the inner ensemble. Note that you can use another classifier as the base estimator, but this will degrades EasyEnsemble to UnderBaggingClassifier and raise a Warning.

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() and predict(). None means 1 unless in a joblib.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 the RandomState instance used by np.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_RandomUnderSampler

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 arrays

The 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

BalanceCascadeClassifier

Ensemble with cascade dynamic under-sampling.

SelfPacedEnsembleClassifier

Ensemble with self-paced dynamic under-sampling.

UnderBaggingClassifier

Bagging with intergrated random under-sampling.

References

1

X. Y. Liu, J. Wu and Z. H. Zhou, “Exploratory Undersampling for Class-Imbalance Learning,” in IEEE Transactions on Systems, Man, and Cybernetics, Part B (Cybernetics), vol. 39, no. 2, pp. 539-550, April 2009.

Examples

>>> from imbalanced_ensemble.ensemble import EasyEnsembleClassifier
>>> 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 = EasyEnsembleClassifier(random_state=0)
>>> clf.fit(X, y)  
EasyEnsembleClassifier(...)
>>> clf.predict(X)  
array([...])

Methods

decision_function(X)

Average of the decision functions of the base classifiers.

fit(X, y, *[, sample_weight, max_samples, ...])

Build an EasyEnsemble classifier from the training set (X, y).

get_params([deep])

Get parameters for this estimator.

predict(X)

Predict class for X.

predict_log_proba(X)

Predict class log-probabilities for X.

predict_proba(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 with k == 1, otherwise k==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 an EasyEnsemble classifier from the training set (X, y).

Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)

The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. DOK and LIL are converted to CSR.

yarray-like of shape (n_samples,)

The target values (class labels).

sample_weightarray-like of shape (n_samples,), default=None

Sample weights. If None, the sample weights are initialized to 1 / n_samples.

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 of labels, if provided in the metric function, or else to the numerical or lexicographical order of the labels in y_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_.

Examples using imbalanced_ensemble.ensemble.EasyEnsembleClassifier