sklearn.dummy.DummyClassifier
class sklearn.dummy.DummyClassifier(*, strategy='prior', random_state=None, constant=None) [source]

DummyClassifier is a classifier that makes predictions using simple rules. This classifier is useful as a simple baseline to compare with other (real) classifiers. Do not use it for real problems. Read more in the User Guide.  New in version 0.13.   Parameters

strategy{“stratified”, “most_frequent”, “prior”, “uniform”, “constant”}, default=”prior”

Strategy to use to generate predictions.  “stratified”: generates predictions by respecting the training set’s class distribution. “most_frequent”: always predicts the most frequent label in the training set. “prior”: always predicts the class that maximizes the class prior (like “most_frequent”) and predict_proba returns the class prior. “uniform”: generates predictions uniformly at random.
“constant”: always predicts a constant label that is provided by the user. This is useful for metrics that evaluate a non-majority class  Changed in version 0.24: The default value of strategy has changed to “prior” in version 0.24.
random_stateint, RandomState instance or None, default=None

Controls the randomness to generate the predictions when strategy='stratified' or strategy='uniform'. Pass an int for reproducible output across multiple function calls. See Glossary.
constantint or str or array-like of shape (n_outputs,)

The explicit constant as predicted by the “constant” strategy. This parameter is useful only for the “constant” strategy.    Attributes

classes_ndarray of shape (n_classes,) or list of such arrays

Class labels for each output.
n_classes_int or list of int

Number of label for each output.
class_prior_ndarray of shape (n_classes,) or list of such arrays

Probability of each class for each output.
n_outputs_int

Number of outputs.
sparse_output_bool

True if the array returned from predict is to be in sparse CSC format. Is automatically set to True if the input y is passed in sparse format.     Examples >>> import numpy as np
>>> from sklearn.dummy import DummyClassifier
>>> X = np.array([-1, 1, 1, 1])
>>> y = np.array([0, 1, 1, 1])
>>> dummy_clf = DummyClassifier(strategy="most_frequent")
>>> dummy_clf.fit(X, y)
DummyClassifier(strategy='most_frequent')
>>> dummy_clf.predict(X)
array([1, 1, 1, 1])
>>> dummy_clf.score(X, y)
0.75
 Methods
fit(X, y[, sample_weight]) Fit the random classifier.
get_params([deep]) Get parameters for this estimator.
predict(X) Perform classification on test vectors X.
predict_log_proba(X) Return log probability estimates for the test vectors X.
predict_proba(X) Return probability estimates for the test vectors X.
score(X, y[, sample_weight]) Returns the mean accuracy on the given test data and labels.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]

Fit the random classifier.  Parameters

Xarray-like of shape (n_samples, n_features)

Training data.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

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

Sample weights.    Returns

selfobject

get_params(deep=True) [source]

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.

predict(X) [source]

Perform classification on test vectors X.  Parameters

Xarray-like of shape (n_samples, n_features)

Test data.    Returns

yarray-like of shape (n_samples,) or (n_samples, n_outputs)

Predicted target values for X.

predict_log_proba(X) [source]

Return log probability estimates for the test vectors X.  Parameters

X{array-like, object with finite length or shape}

Training data, requires length = n_samples    Returns

Pndarray of shape (n_samples, n_classes) or list of such arrays

Returns the log probability of the sample for each class in the model, where classes are ordered arithmetically for each output.

predict_proba(X) [source]

Return probability estimates for the test vectors X.  Parameters

Xarray-like of shape (n_samples, n_features)

Test data.    Returns

Pndarray of shape (n_samples, n_classes) or list of such arrays

Returns the probability of the sample for each class in the model, where classes are ordered arithmetically, for each output.

score(X, y, sample_weight=None) [source]

Returns 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

XNone or array-like of shape (n_samples, n_features)

Test samples. Passing None as test samples gives the same result as passing real test samples, since DummyClassifier operates independently of the sampled observations.
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) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


fit(X, y, sample_weight=None) [source]

Fit the random classifier.  Parameters

Xarray-like of shape (n_samples, n_features)

Training data.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

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

Sample weights.    Returns

selfobject


get_params(deep=True) [source]

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.


predict(X) [source]

Perform classification on test vectors X.  Parameters

Xarray-like of shape (n_samples, n_features)

Test data.    Returns

yarray-like of shape (n_samples,) or (n_samples, n_outputs)

Predicted target values for X.


predict_log_proba(X) [source]

Return log probability estimates for the test vectors X.  Parameters

X{array-like, object with finite length or shape}

Training data, requires length = n_samples    Returns

Pndarray of shape (n_samples, n_classes) or list of such arrays

Returns the log probability of the sample for each class in the model, where classes are ordered arithmetically for each output.


predict_proba(X) [source]

Return probability estimates for the test vectors X.  Parameters

Xarray-like of shape (n_samples, n_features)

Test data.    Returns

Pndarray of shape (n_samples, n_classes) or list of such arrays

Returns the probability of the sample for each class in the model, where classes are ordered arithmetically, for each output.


score(X, y, sample_weight=None) [source]

Returns 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

XNone or array-like of shape (n_samples, n_features)

Test samples. Passing None as test samples gives the same result as passing real test samples, since DummyClassifier operates independently of the sampled observations.
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) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


class sklearn.dummy.DummyRegressor(*, strategy='mean', constant=None, quantile=None) [source]

DummyRegressor is a regressor that makes predictions using simple rules. This regressor is useful as a simple baseline to compare with other (real) regressors. Do not use it for real problems. Read more in the User Guide.  New in version 0.13.   Parameters

strategy{“mean”, “median”, “quantile”, “constant”}, default=”mean”

Strategy to use to generate predictions.  “mean”: always predicts the mean of the training set “median”: always predicts the median of the training set “quantile”: always predicts a specified quantile of the training set, provided with the quantile parameter. “constant”: always predicts a constant value that is provided by the user.
constantint or float or array-like of shape (n_outputs,), default=None

The explicit constant as predicted by the “constant” strategy. This parameter is useful only for the “constant” strategy.
quantilefloat in [0.0, 1.0], default=None

The quantile to predict using the “quantile” strategy. A quantile of 0.5 corresponds to the median, while 0.0 to the minimum and 1.0 to the maximum.    Attributes

constant_ndarray of shape (1, n_outputs)

Mean or median or quantile of the training targets or constant value given by the user.
n_outputs_int

Number of outputs.     Examples >>> import numpy as np
>>> from sklearn.dummy import DummyRegressor
>>> X = np.array([1.0, 2.0, 3.0, 4.0])
>>> y = np.array([2.0, 3.0, 5.0, 10.0])
>>> dummy_regr = DummyRegressor(strategy="mean")
>>> dummy_regr.fit(X, y)
DummyRegressor()
>>> dummy_regr.predict(X)
array([5., 5., 5., 5.])
>>> dummy_regr.score(X, y)
0.0
 Methods
fit(X, y[, sample_weight]) Fit the random regressor.
get_params([deep]) Get parameters for this estimator.
predict(X[, return_std]) Perform classification on test vectors X.
score(X, y[, sample_weight]) Returns the coefficient of determination R^2 of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]

Fit the random regressor.  Parameters

Xarray-like of shape (n_samples, n_features)

Training data.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

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

Sample weights.    Returns

selfobject

get_params(deep=True) [source]

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.

predict(X, return_std=False) [source]

Perform classification on test vectors X.  Parameters

Xarray-like of shape (n_samples, n_features)

Test data.
return_stdbool, default=False

Whether to return the standard deviation of posterior prediction. All zeros in this case.  New in version 0.20.     Returns

yarray-like of shape (n_samples,) or (n_samples, n_outputs)

Predicted target values for X.
y_stdarray-like of shape (n_samples,) or (n_samples, n_outputs)

Standard deviation of predictive distribution of query points.

score(X, y, sample_weight=None) [source]

Returns the coefficient of determination R^2 of the prediction. The coefficient R^2 is defined as (1 - u/v), where u is the residual sum of squares ((y_true - y_pred) ** 2).sum() and v is the total sum of squares ((y_true - y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a R^2 score of 0.0.  Parameters

XNone or array-like of shape (n_samples, n_features)

Test samples. Passing None as test samples gives the same result as passing real test samples, since DummyRegressor operates independently of the sampled observations.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

R^2 of self.predict(X) wrt. y.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


sklearn.dummy.DummyRegressor
class sklearn.dummy.DummyRegressor(*, strategy='mean', constant=None, quantile=None) [source]

DummyRegressor is a regressor that makes predictions using simple rules. This regressor is useful as a simple baseline to compare with other (real) regressors. Do not use it for real problems. Read more in the User Guide.  New in version 0.13.   Parameters

strategy{“mean”, “median”, “quantile”, “constant”}, default=”mean”

Strategy to use to generate predictions.  “mean”: always predicts the mean of the training set “median”: always predicts the median of the training set “quantile”: always predicts a specified quantile of the training set, provided with the quantile parameter. “constant”: always predicts a constant value that is provided by the user.
constantint or float or array-like of shape (n_outputs,), default=None

The explicit constant as predicted by the “constant” strategy. This parameter is useful only for the “constant” strategy.
quantilefloat in [0.0, 1.0], default=None

The quantile to predict using the “quantile” strategy. A quantile of 0.5 corresponds to the median, while 0.0 to the minimum and 1.0 to the maximum.    Attributes

constant_ndarray of shape (1, n_outputs)

Mean or median or quantile of the training targets or constant value given by the user.
n_outputs_int

Number of outputs.     Examples >>> import numpy as np
>>> from sklearn.dummy import DummyRegressor
>>> X = np.array([1.0, 2.0, 3.0, 4.0])
>>> y = np.array([2.0, 3.0, 5.0, 10.0])
>>> dummy_regr = DummyRegressor(strategy="mean")
>>> dummy_regr.fit(X, y)
DummyRegressor()
>>> dummy_regr.predict(X)
array([5., 5., 5., 5.])
>>> dummy_regr.score(X, y)
0.0
 Methods
fit(X, y[, sample_weight]) Fit the random regressor.
get_params([deep]) Get parameters for this estimator.
predict(X[, return_std]) Perform classification on test vectors X.
score(X, y[, sample_weight]) Returns the coefficient of determination R^2 of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y, sample_weight=None) [source]

Fit the random regressor.  Parameters

Xarray-like of shape (n_samples, n_features)

Training data.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

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

Sample weights.    Returns

selfobject

get_params(deep=True) [source]

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.

predict(X, return_std=False) [source]

Perform classification on test vectors X.  Parameters

Xarray-like of shape (n_samples, n_features)

Test data.
return_stdbool, default=False

Whether to return the standard deviation of posterior prediction. All zeros in this case.  New in version 0.20.     Returns

yarray-like of shape (n_samples,) or (n_samples, n_outputs)

Predicted target values for X.
y_stdarray-like of shape (n_samples,) or (n_samples, n_outputs)

Standard deviation of predictive distribution of query points.

score(X, y, sample_weight=None) [source]

Returns the coefficient of determination R^2 of the prediction. The coefficient R^2 is defined as (1 - u/v), where u is the residual sum of squares ((y_true - y_pred) ** 2).sum() and v is the total sum of squares ((y_true - y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a R^2 score of 0.0.  Parameters

XNone or array-like of shape (n_samples, n_features)

Test samples. Passing None as test samples gives the same result as passing real test samples, since DummyRegressor operates independently of the sampled observations.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

R^2 of self.predict(X) wrt. y.

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

 Examples using sklearn.dummy.DummyRegressor

  Poisson regression and non-normal loss


fit(X, y, sample_weight=None) [source]

Fit the random regressor.  Parameters

Xarray-like of shape (n_samples, n_features)

Training data.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

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

Sample weights.    Returns

selfobject


predict(X, return_std=False) [source]

Perform classification on test vectors X.  Parameters

Xarray-like of shape (n_samples, n_features)

Test data.
return_stdbool, default=False

Whether to return the standard deviation of posterior prediction. All zeros in this case.  New in version 0.20.     Returns

yarray-like of shape (n_samples,) or (n_samples, n_outputs)

Predicted target values for X.
y_stdarray-like of shape (n_samples,) or (n_samples, n_outputs)

Standard deviation of predictive distribution of query points.


score(X, y, sample_weight=None) [source]

Returns the coefficient of determination R^2 of the prediction. The coefficient R^2 is defined as (1 - u/v), where u is the residual sum of squares ((y_true - y_pred) ** 2).sum() and v is the total sum of squares ((y_true - y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a R^2 score of 0.0.  Parameters

XNone or array-like of shape (n_samples, n_features)

Test samples. Passing None as test samples gives the same result as passing real test samples, since DummyRegressor operates independently of the sampled observations.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

R^2 of self.predict(X) wrt. y.


class sklearn.ensemble.AdaBoostClassifier(base_estimator=None, *, n_estimators=50, learning_rate=1.0, algorithm='SAMME.R', random_state=None) [source]

An AdaBoost classifier. An AdaBoost [1] classifier is a meta-estimator that begins by fitting a classifier on the original dataset and then fits additional copies of the classifier on the same dataset but where the weights of incorrectly classified instances are adjusted such that subsequent classifiers focus more on difficult cases. This class implements the algorithm known as AdaBoost-SAMME [2]. Read more in the User Guide.  New in version 0.14.   Parameters

base_estimatorobject, default=None

The base estimator from which the boosted ensemble is built. Support for sample weighting is required, as well as proper classes_ and n_classes_ attributes. If None, then the base estimator is DecisionTreeClassifier initialized with max_depth=1.
n_estimatorsint, default=50

The maximum number of estimators at which boosting is terminated. In case of perfect fit, the learning procedure is stopped early.
learning_ratefloat, default=1.

Learning rate shrinks the contribution of each classifier by learning_rate. There is a trade-off between learning_rate and n_estimators.
algorithm{‘SAMME’, ‘SAMME.R’}, default=’SAMME.R’

If ‘SAMME.R’ then use the SAMME.R real boosting algorithm. base_estimator must support calculation of class probabilities. If ‘SAMME’ then use the SAMME discrete boosting algorithm. The SAMME.R algorithm typically converges faster than SAMME, achieving a lower test error with fewer boosting iterations.
random_stateint, RandomState instance or None, default=None

Controls the random seed given at each base_estimator at each boosting iteration. Thus, it is only used when base_estimator exposes a random_state. Pass an int for reproducible output across multiple function calls. See Glossary.    Attributes

base_estimator_estimator

The base estimator from which the ensemble is grown.
estimators_list of classifiers

The collection of fitted sub-estimators.
classes_ndarray of shape (n_classes,)

The classes labels.
n_classes_int

The number of classes.
estimator_weights_ndarray of floats

Weights for each estimator in the boosted ensemble.
estimator_errors_ndarray of floats

Classification error for each estimator in the boosted ensemble.
feature_importances_ndarray of shape (n_features,)

The impurity-based feature importances.      See also
AdaBoostRegressor

An AdaBoost regressor that begins by fitting a regressor on the original dataset and then fits additional copies of the regressor on the same dataset but where the weights of instances are adjusted according to the error of the current prediction.
GradientBoostingClassifier

GB builds an additive model in a forward stage-wise fashion. Regression trees are fit on the negative gradient of the binomial or multinomial deviance loss function. Binary classification is a special case where only a single regression tree is induced.
sklearn.tree.DecisionTreeClassifier

A non-parametric supervised learning method used for classification. Creates a model that predicts the value of a target variable by learning simple decision rules inferred from the data features.    References
1
Y. Freund, R. Schapire, “A Decision-Theoretic Generalization of on-Line Learning and an Application to Boosting”, 1995.
2
 Zhu, H. Zou, S. Rosset, T. Hastie, “Multi-class AdaBoost”, 2009.    Examples >>> from sklearn.ensemble import AdaBoostClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=1000, n_features=4,
...                            n_informative=2, n_redundant=0,
...                            random_state=0, shuffle=False)
>>> clf = AdaBoostClassifier(n_estimators=100, random_state=0)
>>> clf.fit(X, y)
AdaBoostClassifier(n_estimators=100, random_state=0)
>>> clf.predict([[0, 0, 0, 0]])
array([1])
>>> clf.score(X, y)
0.983...
 Methods
decision_function(X) Compute the decision function of X.
fit(X, y[, sample_weight]) Build a boosted classifier from the training set (X, y).
get_params([deep]) Get parameters for this estimator.
predict(X) Predict classes 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) Set the parameters of this estimator.
staged_decision_function(X) Compute decision function of X for each boosting iteration.
staged_predict(X) Return staged predictions for X.
staged_predict_proba(X) Predict class probabilities for X.
staged_score(X, y[, sample_weight]) Return staged scores for X, y.
decision_function(X) [source]

Compute the decision function of X.  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. COO, DOK, and LIL are converted to CSR.    Returns

scorendarray of shape of (n_samples, k)

The decision function of the input samples. The order of outputs is the same of that of the classes_ attribute. Binary classification is a special cases with k == 1, otherwise k==n_classes. For binary classification, values closer to -1 or 1 mean more like the first or second class in classes_, respectively.

property feature_importances_
The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative.  Returns

feature_importances_ndarray of shape (n_features,)

The feature importances.

fit(X, y, sample_weight=None) [source]

Build a boosted 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. COO, 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.    Returns

selfobject

Fitted estimator.

get_params(deep=True) [source]

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.

predict(X) [source]

Predict classes for X. The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble.  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. COO, DOK, and LIL are converted to CSR.    Returns

yndarray of shape (n_samples,)

The predicted classes.

predict_log_proba(X) [source]

Predict class log-probabilities for X. The predicted class log-probabilities of an input sample is computed as the weighted mean predicted class log-probabilities of the classifiers in the ensemble.  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. COO, DOK, and LIL are converted to CSR.    Returns

pndarray of shape (n_samples, n_classes)

The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.

predict_proba(X) [source]

Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the weighted mean predicted class probabilities of the classifiers in the ensemble.  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. COO, DOK, and LIL are converted to CSR.    Returns

pndarray of shape (n_samples, n_classes)

The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.

score(X, y, sample_weight=None) [source]

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) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

staged_decision_function(X) [source]

Compute decision function of X for each boosting iteration. This method allows monitoring (i.e. determine error on testing set) after each boosting iteration.  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. COO, DOK, and LIL are converted to CSR.    Yields

scoregenerator of ndarray of shape (n_samples, k)

The decision function of the input samples. The order of outputs is the same of that of the classes_ attribute. Binary classification is a special cases with k == 1, otherwise k==n_classes. For binary classification, values closer to -1 or 1 mean more like the first or second class in classes_, respectively.

staged_predict(X) [source]

Return staged predictions for X. The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble. This generator method yields the ensemble prediction after each iteration of boosting and therefore allows monitoring, such as to determine the prediction on a test set after each boost.  Parameters

Xarray-like of shape (n_samples, n_features)

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

ygenerator of ndarray of shape (n_samples,)

The predicted classes.

staged_predict_proba(X) [source]

Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the weighted mean predicted class probabilities of the classifiers in the ensemble. This generator method yields the ensemble predicted class probabilities after each iteration of boosting and therefore allows monitoring, such as to determine the predicted class probabilities on a test set after each boost.  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. COO, DOK, and LIL are converted to CSR.    Yields

pgenerator of ndarray of shape (n_samples,)

The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.

staged_score(X, y, sample_weight=None) [source]

Return staged scores for X, y. This generator method yields the ensemble score after each iteration of boosting and therefore allows monitoring, such as to determine the score on a test set after each boost.  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. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)

Labels for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Yields

zfloat


sklearn.ensemble.AdaBoostClassifier
class sklearn.ensemble.AdaBoostClassifier(base_estimator=None, *, n_estimators=50, learning_rate=1.0, algorithm='SAMME.R', random_state=None) [source]

An AdaBoost classifier. An AdaBoost [1] classifier is a meta-estimator that begins by fitting a classifier on the original dataset and then fits additional copies of the classifier on the same dataset but where the weights of incorrectly classified instances are adjusted such that subsequent classifiers focus more on difficult cases. This class implements the algorithm known as AdaBoost-SAMME [2]. Read more in the User Guide.  New in version 0.14.   Parameters

base_estimatorobject, default=None

The base estimator from which the boosted ensemble is built. Support for sample weighting is required, as well as proper classes_ and n_classes_ attributes. If None, then the base estimator is DecisionTreeClassifier initialized with max_depth=1.
n_estimatorsint, default=50

The maximum number of estimators at which boosting is terminated. In case of perfect fit, the learning procedure is stopped early.
learning_ratefloat, default=1.

Learning rate shrinks the contribution of each classifier by learning_rate. There is a trade-off between learning_rate and n_estimators.
algorithm{‘SAMME’, ‘SAMME.R’}, default=’SAMME.R’

If ‘SAMME.R’ then use the SAMME.R real boosting algorithm. base_estimator must support calculation of class probabilities. If ‘SAMME’ then use the SAMME discrete boosting algorithm. The SAMME.R algorithm typically converges faster than SAMME, achieving a lower test error with fewer boosting iterations.
random_stateint, RandomState instance or None, default=None

Controls the random seed given at each base_estimator at each boosting iteration. Thus, it is only used when base_estimator exposes a random_state. Pass an int for reproducible output across multiple function calls. See Glossary.    Attributes

base_estimator_estimator

The base estimator from which the ensemble is grown.
estimators_list of classifiers

The collection of fitted sub-estimators.
classes_ndarray of shape (n_classes,)

The classes labels.
n_classes_int

The number of classes.
estimator_weights_ndarray of floats

Weights for each estimator in the boosted ensemble.
estimator_errors_ndarray of floats

Classification error for each estimator in the boosted ensemble.
feature_importances_ndarray of shape (n_features,)

The impurity-based feature importances.      See also
AdaBoostRegressor

An AdaBoost regressor that begins by fitting a regressor on the original dataset and then fits additional copies of the regressor on the same dataset but where the weights of instances are adjusted according to the error of the current prediction.
GradientBoostingClassifier

GB builds an additive model in a forward stage-wise fashion. Regression trees are fit on the negative gradient of the binomial or multinomial deviance loss function. Binary classification is a special case where only a single regression tree is induced.
sklearn.tree.DecisionTreeClassifier

A non-parametric supervised learning method used for classification. Creates a model that predicts the value of a target variable by learning simple decision rules inferred from the data features.    References
1
Y. Freund, R. Schapire, “A Decision-Theoretic Generalization of on-Line Learning and an Application to Boosting”, 1995.
2
 Zhu, H. Zou, S. Rosset, T. Hastie, “Multi-class AdaBoost”, 2009.    Examples >>> from sklearn.ensemble import AdaBoostClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=1000, n_features=4,
...                            n_informative=2, n_redundant=0,
...                            random_state=0, shuffle=False)
>>> clf = AdaBoostClassifier(n_estimators=100, random_state=0)
>>> clf.fit(X, y)
AdaBoostClassifier(n_estimators=100, random_state=0)
>>> clf.predict([[0, 0, 0, 0]])
array([1])
>>> clf.score(X, y)
0.983...
 Methods
decision_function(X) Compute the decision function of X.
fit(X, y[, sample_weight]) Build a boosted classifier from the training set (X, y).
get_params([deep]) Get parameters for this estimator.
predict(X) Predict classes 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) Set the parameters of this estimator.
staged_decision_function(X) Compute decision function of X for each boosting iteration.
staged_predict(X) Return staged predictions for X.
staged_predict_proba(X) Predict class probabilities for X.
staged_score(X, y[, sample_weight]) Return staged scores for X, y.
decision_function(X) [source]

Compute the decision function of X.  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. COO, DOK, and LIL are converted to CSR.    Returns

scorendarray of shape of (n_samples, k)

The decision function of the input samples. The order of outputs is the same of that of the classes_ attribute. Binary classification is a special cases with k == 1, otherwise k==n_classes. For binary classification, values closer to -1 or 1 mean more like the first or second class in classes_, respectively.

property feature_importances_
The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative.  Returns

feature_importances_ndarray of shape (n_features,)

The feature importances.

fit(X, y, sample_weight=None) [source]

Build a boosted 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. COO, 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.    Returns

selfobject

Fitted estimator.

get_params(deep=True) [source]

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.

predict(X) [source]

Predict classes for X. The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble.  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. COO, DOK, and LIL are converted to CSR.    Returns

yndarray of shape (n_samples,)

The predicted classes.

predict_log_proba(X) [source]

Predict class log-probabilities for X. The predicted class log-probabilities of an input sample is computed as the weighted mean predicted class log-probabilities of the classifiers in the ensemble.  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. COO, DOK, and LIL are converted to CSR.    Returns

pndarray of shape (n_samples, n_classes)

The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.

predict_proba(X) [source]

Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the weighted mean predicted class probabilities of the classifiers in the ensemble.  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. COO, DOK, and LIL are converted to CSR.    Returns

pndarray of shape (n_samples, n_classes)

The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.

score(X, y, sample_weight=None) [source]

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) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

staged_decision_function(X) [source]

Compute decision function of X for each boosting iteration. This method allows monitoring (i.e. determine error on testing set) after each boosting iteration.  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. COO, DOK, and LIL are converted to CSR.    Yields

scoregenerator of ndarray of shape (n_samples, k)

The decision function of the input samples. The order of outputs is the same of that of the classes_ attribute. Binary classification is a special cases with k == 1, otherwise k==n_classes. For binary classification, values closer to -1 or 1 mean more like the first or second class in classes_, respectively.

staged_predict(X) [source]

Return staged predictions for X. The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble. This generator method yields the ensemble prediction after each iteration of boosting and therefore allows monitoring, such as to determine the prediction on a test set after each boost.  Parameters

Xarray-like of shape (n_samples, n_features)

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

ygenerator of ndarray of shape (n_samples,)

The predicted classes.

staged_predict_proba(X) [source]

Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the weighted mean predicted class probabilities of the classifiers in the ensemble. This generator method yields the ensemble predicted class probabilities after each iteration of boosting and therefore allows monitoring, such as to determine the predicted class probabilities on a test set after each boost.  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. COO, DOK, and LIL are converted to CSR.    Yields

pgenerator of ndarray of shape (n_samples,)

The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.

staged_score(X, y, sample_weight=None) [source]

Return staged scores for X, y. This generator method yields the ensemble score after each iteration of boosting and therefore allows monitoring, such as to determine the score on a test set after each boost.  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. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)

Labels for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Yields

zfloat

 Examples using sklearn.ensemble.AdaBoostClassifier

  Classifier comparison

  Two-class AdaBoost

  Multi-class AdaBoosted Decision Trees

  Discrete versus Real AdaBoost

  Plot the decision surfaces of ensembles of trees on the iris dataset


decision_function(X) [source]

Compute the decision function of X.  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. COO, DOK, and LIL are converted to CSR.    Returns

scorendarray of shape of (n_samples, k)

The decision function of the input samples. The order of outputs is the same of that of the classes_ attribute. Binary classification is a special cases with k == 1, otherwise k==n_classes. For binary classification, values closer to -1 or 1 mean more like the first or second class in classes_, respectively.


property feature_importances_
The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative.  Returns

feature_importances_ndarray of shape (n_features,)

The feature importances.


fit(X, y, sample_weight=None) [source]

Build a boosted 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. COO, 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.    Returns

selfobject

Fitted estimator.


predict(X) [source]

Predict classes for X. The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble.  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. COO, DOK, and LIL are converted to CSR.    Returns

yndarray of shape (n_samples,)

The predicted classes.


predict_log_proba(X) [source]

Predict class log-probabilities for X. The predicted class log-probabilities of an input sample is computed as the weighted mean predicted class log-probabilities of the classifiers in the ensemble.  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. COO, DOK, and LIL are converted to CSR.    Returns

pndarray of shape (n_samples, n_classes)

The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.


predict_proba(X) [source]

Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the weighted mean predicted class probabilities of the classifiers in the ensemble.  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. COO, DOK, and LIL are converted to CSR.    Returns

pndarray of shape (n_samples, n_classes)

The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.


score(X, y, sample_weight=None) [source]

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.


staged_decision_function(X) [source]

Compute decision function of X for each boosting iteration. This method allows monitoring (i.e. determine error on testing set) after each boosting iteration.  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. COO, DOK, and LIL are converted to CSR.    Yields

scoregenerator of ndarray of shape (n_samples, k)

The decision function of the input samples. The order of outputs is the same of that of the classes_ attribute. Binary classification is a special cases with k == 1, otherwise k==n_classes. For binary classification, values closer to -1 or 1 mean more like the first or second class in classes_, respectively.


staged_predict(X) [source]

Return staged predictions for X. The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble. This generator method yields the ensemble prediction after each iteration of boosting and therefore allows monitoring, such as to determine the prediction on a test set after each boost.  Parameters

Xarray-like of shape (n_samples, n_features)

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

ygenerator of ndarray of shape (n_samples,)

The predicted classes.


staged_predict_proba(X) [source]

Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the weighted mean predicted class probabilities of the classifiers in the ensemble. This generator method yields the ensemble predicted class probabilities after each iteration of boosting and therefore allows monitoring, such as to determine the predicted class probabilities on a test set after each boost.  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. COO, DOK, and LIL are converted to CSR.    Yields

pgenerator of ndarray of shape (n_samples,)

The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.


staged_score(X, y, sample_weight=None) [source]

Return staged scores for X, y. This generator method yields the ensemble score after each iteration of boosting and therefore allows monitoring, such as to determine the score on a test set after each boost.  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. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)

Labels for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Yields

zfloat


class sklearn.ensemble.AdaBoostRegressor(base_estimator=None, *, n_estimators=50, learning_rate=1.0, loss='linear', random_state=None) [source]

An AdaBoost regressor. An AdaBoost [1] regressor is a meta-estimator that begins by fitting a regressor on the original dataset and then fits additional copies of the regressor on the same dataset but where the weights of instances are adjusted according to the error of the current prediction. As such, subsequent regressors focus more on difficult cases. This class implements the algorithm known as AdaBoost.R2 [2]. Read more in the User Guide.  New in version 0.14.   Parameters

base_estimatorobject, default=None

The base estimator from which the boosted ensemble is built. If None, then the base estimator is DecisionTreeRegressor initialized with max_depth=3.
n_estimatorsint, default=50

The maximum number of estimators at which boosting is terminated. In case of perfect fit, the learning procedure is stopped early.
learning_ratefloat, default=1.

Learning rate shrinks the contribution of each regressor by learning_rate. There is a trade-off between learning_rate and n_estimators.
loss{‘linear’, ‘square’, ‘exponential’}, default=’linear’

The loss function to use when updating the weights after each boosting iteration.
random_stateint, RandomState instance or None, default=None

Controls the random seed given at each base_estimator at each boosting iteration. Thus, it is only used when base_estimator exposes a random_state. In addition, it controls the bootstrap of the weights used to train the base_estimator at each boosting iteration. Pass an int for reproducible output across multiple function calls. See Glossary.    Attributes

base_estimator_estimator

The base estimator from which the ensemble is grown.
estimators_list of classifiers

The collection of fitted sub-estimators.
estimator_weights_ndarray of floats

Weights for each estimator in the boosted ensemble.
estimator_errors_ndarray of floats

Regression error for each estimator in the boosted ensemble.
feature_importances_ndarray of shape (n_features,)

The impurity-based feature importances.      See also
AdaBoostClassifier, GradientBoostingRegressor

sklearn.tree.DecisionTreeRegressor

  References
1
Y. Freund, R. Schapire, “A Decision-Theoretic Generalization of on-Line Learning and an Application to Boosting”, 1995.
2
 Drucker, “Improving Regressors using Boosting Techniques”, 1997.    Examples >>> from sklearn.ensemble import AdaBoostRegressor
>>> from sklearn.datasets import make_regression
>>> X, y = make_regression(n_features=4, n_informative=2,
...                        random_state=0, shuffle=False)
>>> regr = AdaBoostRegressor(random_state=0, n_estimators=100)
>>> regr.fit(X, y)
AdaBoostRegressor(n_estimators=100, random_state=0)
>>> regr.predict([[0, 0, 0, 0]])
array([4.7972...])
>>> regr.score(X, y)
0.9771...
 Methods
fit(X, y[, sample_weight]) Build a boosted regressor from the training set (X, y).
get_params([deep]) Get parameters for this estimator.
predict(X) Predict regression value for X.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
staged_predict(X) Return staged predictions for X.
staged_score(X, y[, sample_weight]) Return staged scores for X, y.
property feature_importances_
The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative.  Returns

feature_importances_ndarray of shape (n_features,)

The feature importances.

fit(X, y, sample_weight=None) [source]

Build a boosted regressor 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. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)

The target values (real numbers).
sample_weightarray-like of shape (n_samples,), default=None

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

selfobject

get_params(deep=True) [source]

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.

predict(X) [source]

Predict regression value for X. The predicted regression value of an input sample is computed as the weighted median prediction of the classifiers in the ensemble.  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. COO, DOK, and LIL are converted to CSR.    Returns

yndarray of shape (n_samples,)

The predicted regression values.

score(X, y, sample_weight=None) [source]

Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

\(R^2\) of self.predict(X) wrt. y.     Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

staged_predict(X) [source]

Return staged predictions for X. The predicted regression value of an input sample is computed as the weighted median prediction of the classifiers in the ensemble. This generator method yields the ensemble prediction after each iteration of boosting and therefore allows monitoring, such as to determine the prediction on a test set after each boost.  Parameters

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

The training input samples.    Yields

ygenerator of ndarray of shape (n_samples,)

The predicted regression values.

staged_score(X, y, sample_weight=None) [source]

Return staged scores for X, y. This generator method yields the ensemble score after each iteration of boosting and therefore allows monitoring, such as to determine the score on a test set after each boost.  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. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)

Labels for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Yields

zfloat


sklearn.ensemble.AdaBoostRegressor
class sklearn.ensemble.AdaBoostRegressor(base_estimator=None, *, n_estimators=50, learning_rate=1.0, loss='linear', random_state=None) [source]

An AdaBoost regressor. An AdaBoost [1] regressor is a meta-estimator that begins by fitting a regressor on the original dataset and then fits additional copies of the regressor on the same dataset but where the weights of instances are adjusted according to the error of the current prediction. As such, subsequent regressors focus more on difficult cases. This class implements the algorithm known as AdaBoost.R2 [2]. Read more in the User Guide.  New in version 0.14.   Parameters

base_estimatorobject, default=None

The base estimator from which the boosted ensemble is built. If None, then the base estimator is DecisionTreeRegressor initialized with max_depth=3.
n_estimatorsint, default=50

The maximum number of estimators at which boosting is terminated. In case of perfect fit, the learning procedure is stopped early.
learning_ratefloat, default=1.

Learning rate shrinks the contribution of each regressor by learning_rate. There is a trade-off between learning_rate and n_estimators.
loss{‘linear’, ‘square’, ‘exponential’}, default=’linear’

The loss function to use when updating the weights after each boosting iteration.
random_stateint, RandomState instance or None, default=None

Controls the random seed given at each base_estimator at each boosting iteration. Thus, it is only used when base_estimator exposes a random_state. In addition, it controls the bootstrap of the weights used to train the base_estimator at each boosting iteration. Pass an int for reproducible output across multiple function calls. See Glossary.    Attributes

base_estimator_estimator

The base estimator from which the ensemble is grown.
estimators_list of classifiers

The collection of fitted sub-estimators.
estimator_weights_ndarray of floats

Weights for each estimator in the boosted ensemble.
estimator_errors_ndarray of floats

Regression error for each estimator in the boosted ensemble.
feature_importances_ndarray of shape (n_features,)

The impurity-based feature importances.      See also
AdaBoostClassifier, GradientBoostingRegressor

sklearn.tree.DecisionTreeRegressor

  References
1
Y. Freund, R. Schapire, “A Decision-Theoretic Generalization of on-Line Learning and an Application to Boosting”, 1995.
2
 Drucker, “Improving Regressors using Boosting Techniques”, 1997.    Examples >>> from sklearn.ensemble import AdaBoostRegressor
>>> from sklearn.datasets import make_regression
>>> X, y = make_regression(n_features=4, n_informative=2,
...                        random_state=0, shuffle=False)
>>> regr = AdaBoostRegressor(random_state=0, n_estimators=100)
>>> regr.fit(X, y)
AdaBoostRegressor(n_estimators=100, random_state=0)
>>> regr.predict([[0, 0, 0, 0]])
array([4.7972...])
>>> regr.score(X, y)
0.9771...
 Methods
fit(X, y[, sample_weight]) Build a boosted regressor from the training set (X, y).
get_params([deep]) Get parameters for this estimator.
predict(X) Predict regression value for X.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
staged_predict(X) Return staged predictions for X.
staged_score(X, y[, sample_weight]) Return staged scores for X, y.
property feature_importances_
The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative.  Returns

feature_importances_ndarray of shape (n_features,)

The feature importances.

fit(X, y, sample_weight=None) [source]

Build a boosted regressor 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. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)

The target values (real numbers).
sample_weightarray-like of shape (n_samples,), default=None

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

selfobject

get_params(deep=True) [source]

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.

predict(X) [source]

Predict regression value for X. The predicted regression value of an input sample is computed as the weighted median prediction of the classifiers in the ensemble.  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. COO, DOK, and LIL are converted to CSR.    Returns

yndarray of shape (n_samples,)

The predicted regression values.

score(X, y, sample_weight=None) [source]

Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

\(R^2\) of self.predict(X) wrt. y.     Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).

set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.

staged_predict(X) [source]

Return staged predictions for X. The predicted regression value of an input sample is computed as the weighted median prediction of the classifiers in the ensemble. This generator method yields the ensemble prediction after each iteration of boosting and therefore allows monitoring, such as to determine the prediction on a test set after each boost.  Parameters

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

The training input samples.    Yields

ygenerator of ndarray of shape (n_samples,)

The predicted regression values.

staged_score(X, y, sample_weight=None) [source]

Return staged scores for X, y. This generator method yields the ensemble score after each iteration of boosting and therefore allows monitoring, such as to determine the score on a test set after each boost.  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. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)

Labels for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Yields

zfloat

 Examples using sklearn.ensemble.AdaBoostRegressor

  Decision Tree Regression with AdaBoost


fit(X, y, sample_weight=None) [source]

Build a boosted regressor 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. COO, DOK, and LIL are converted to CSR.
yarray-like of shape (n_samples,)

The target values (real numbers).
sample_weightarray-like of shape (n_samples,), default=None

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

selfobject


get_params(deep=True) [source]

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.


predict(X) [source]

Predict regression value for X. The predicted regression value of an input sample is computed as the weighted median prediction of the classifiers in the ensemble.  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. COO, DOK, and LIL are converted to CSR.    Returns

yndarray of shape (n_samples,)

The predicted regression values.


score(X, y, sample_weight=None) [source]

Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.  Parameters

Xarray-like of shape (n_samples, n_features)

Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.
sample_weightarray-like of shape (n_samples,), default=None

Sample weights.    Returns

scorefloat

\(R^2\) of self.predict(X) wrt. y.     Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).


set_params(**params) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


staged_predict(X) [source]

Return staged predictions for X. The predicted regression value of an input sample is computed as the weighted median prediction of the classifiers in the ensemble. This generator method yields the ensemble prediction after each iteration of boosting and therefore allows monitoring, such as to determine the prediction on a test set after each boost.  Parameters

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

The training input samples.    Yields

ygenerator of ndarray of shape (n_samples,)

The predicted regression values.


class sklearn.ensemble.BaggingClassifier(base_estimator=None, n_estimators=10, *, 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) [source]

A Bagging classifier. A Bagging classifier is an ensemble meta-estimator that fits base classifiers each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a final prediction. Such a meta-estimator can typically be used as a way to reduce the variance of a black-box estimator (e.g., a decision tree), by introducing randomization into its construction procedure and then making an ensemble out of it. This algorithm encompasses several works from the literature. When random subsets of the dataset are drawn as random subsets of the samples, then this algorithm is known as Pasting [1]. If samples are drawn with replacement, then the method is known as Bagging [2]. When random subsets of the dataset are drawn as random subsets of the features, then the method is known as Random Subspaces [3]. Finally, when base estimators are built on subsets of both samples and features, then the method is known as Random Patches [4]. Read more in the User Guide.  New in version 0.15.   Parameters

base_estimatorobject, default=None

The base estimator to fit on random subsets of the dataset. If None, then the base estimator is a DecisionTreeClassifier.
n_estimatorsint, default=10

The number of base estimators in the ensemble.
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 the Glossary.  New in version 0.17: warm_start constructor parameter.
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

Controls the random resampling of the original dataset (sample wise and feature wise). 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. See Glossary.
verboseint, default=0

Controls the verbosity when fitting and predicting.    Attributes

base_estimator_estimator

The base estimator from which the ensemble is grown.
n_features_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.
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.     References
1
L. Breiman, “Pasting small votes for classification in large databases and on-line”, Machine Learning, 36(1), 85-103, 1999.
2
L. Breiman, “Bagging predictors”, Machine Learning, 24(2), 123-140, 1996.
3
T. Ho, “The random subspace method for constructing decision forests”, Pattern Analysis and Machine Intelligence, 20(8), 832-844, 1998.
4
G. Louppe and P. Geurts, “Ensembles on Random Patches”, Machine Learning and Knowledge Discovery in Databases, 346-361, 2012.   Examples >>> from sklearn.svm import SVC
>>> from sklearn.ensemble import BaggingClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=100, n_features=4,
...                            n_informative=2, n_redundant=0,
...                            random_state=0, shuffle=False)
>>> clf = BaggingClassifier(base_estimator=SVC(),
...                         n_estimators=10, random_state=0).fit(X, y)
>>> clf.predict([[0, 0, 0, 0]])
array([1])
 Methods
decision_function(X) Average of the decision functions of the base classifiers.
fit(X, y[, sample_weight]) Build a Bagging ensemble of estimators from the training
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) Set the parameters of this estimator.
decision_function(X) [source]

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) [source]

 Build a Bagging 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.    Returns

selfobject

get_params(deep=True) [source]

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.

predict(X) [source]

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) [source]

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) [source]

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) [source]

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) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


sklearn.ensemble.BaggingClassifier
class sklearn.ensemble.BaggingClassifier(base_estimator=None, n_estimators=10, *, 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) [source]

A Bagging classifier. A Bagging classifier is an ensemble meta-estimator that fits base classifiers each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a final prediction. Such a meta-estimator can typically be used as a way to reduce the variance of a black-box estimator (e.g., a decision tree), by introducing randomization into its construction procedure and then making an ensemble out of it. This algorithm encompasses several works from the literature. When random subsets of the dataset are drawn as random subsets of the samples, then this algorithm is known as Pasting [1]. If samples are drawn with replacement, then the method is known as Bagging [2]. When random subsets of the dataset are drawn as random subsets of the features, then the method is known as Random Subspaces [3]. Finally, when base estimators are built on subsets of both samples and features, then the method is known as Random Patches [4]. Read more in the User Guide.  New in version 0.15.   Parameters

base_estimatorobject, default=None

The base estimator to fit on random subsets of the dataset. If None, then the base estimator is a DecisionTreeClassifier.
n_estimatorsint, default=10

The number of base estimators in the ensemble.
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 the Glossary.  New in version 0.17: warm_start constructor parameter.
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

Controls the random resampling of the original dataset (sample wise and feature wise). 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. See Glossary.
verboseint, default=0

Controls the verbosity when fitting and predicting.    Attributes

base_estimator_estimator

The base estimator from which the ensemble is grown.
n_features_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.
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.     References
1
L. Breiman, “Pasting small votes for classification in large databases and on-line”, Machine Learning, 36(1), 85-103, 1999.
2
L. Breiman, “Bagging predictors”, Machine Learning, 24(2), 123-140, 1996.
3
T. Ho, “The random subspace method for constructing decision forests”, Pattern Analysis and Machine Intelligence, 20(8), 832-844, 1998.
4
G. Louppe and P. Geurts, “Ensembles on Random Patches”, Machine Learning and Knowledge Discovery in Databases, 346-361, 2012.   Examples >>> from sklearn.svm import SVC
>>> from sklearn.ensemble import BaggingClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=100, n_features=4,
...                            n_informative=2, n_redundant=0,
...                            random_state=0, shuffle=False)
>>> clf = BaggingClassifier(base_estimator=SVC(),
...                         n_estimators=10, random_state=0).fit(X, y)
>>> clf.predict([[0, 0, 0, 0]])
array([1])
 Methods
decision_function(X) Average of the decision functions of the base classifiers.
fit(X, y[, sample_weight]) Build a Bagging ensemble of estimators from the training
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) Set the parameters of this estimator.
decision_function(X) [source]

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) [source]

 Build a Bagging 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.    Returns

selfobject

get_params(deep=True) [source]

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.

predict(X) [source]

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) [source]

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) [source]

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) [source]

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) [source]

Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.  Parameters

**paramsdict

Estimator parameters.    Returns

selfestimator instance

Estimator instance.


decision_function(X) [source]

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) [source]

 Build a Bagging 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.    Returns

selfobject


predict(X) [source]

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) [source]

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) [source]

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) [source]

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.