Dimensionality reduction using truncated SVD (aka LSA).
This transformer performs linear dimensionality reduction by means of truncated singular value decomposition (SVD). Contrary to PCA, this estimator does not center the data before computing the singular value decomposition. This means it can work with sparse matrices efficiently.
In particular, truncated SVD works on term count/tf-idf matrices as returned by the vectorizers in sklearn.feature_extraction.text. In that context, it is known as latent semantic analysis (LSA).
This estimator supports two algorithms: a fast randomized SVD solver, and a “naive” algorithm that uses ARPACK as an eigensolver on X * X.T or X.T * X, whichever is more efficient.
Read more in the User Guide.
Desired dimensionality of output data. Must be strictly less than the number of features. The default value is useful for visualisation. For LSA, a value of 100 is recommended.
SVD solver to use. Either “arpack” for the ARPACK wrapper in SciPy (scipy.sparse.linalg.svds), or “randomized” for the randomized algorithm due to Halko (2009).
Number of iterations for randomized SVD solver. Not used by ARPACK. The default is larger than the default in randomized_svd to handle sparse matrices that may have large slowly decaying spectrum.
Used during randomized svd. Pass an int for reproducible results across multiple function calls. See Glossary.
Tolerance for ARPACK. 0 means machine precision. Ignored by randomized SVD solver.
The variance of the training samples transformed by a projection to each component.
Percentage of variance explained by each of the selected components.
The singular values corresponding to each of the selected components. The singular values are equal to the 2-norms of the n_components variables in the lower-dimensional space.
See also
SVD suffers from a problem called “sign indeterminacy”, which means the sign of the components_ and the output from transform depend on the algorithm and random state. To work around this, fit instances of this class to data once, then keep the instance around to do transformations.
Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions Halko, et al., 2009 (arXiv:909) https://arxiv.org/pdf/0909.4061.pdf
fit(X[, y])
Fit model on training data X.
fit_transform(X[, y])
Fit model to X and perform dimensionality reduction on X.
get_params([deep])
Get parameters for this estimator.
inverse_transform(X)
Transform X back to its original space.
set_params(**params)
Set the parameters of this estimator.
transform(X)
Perform dimensionality reduction on X.
Fit model on training data X.
Training data.
Returns the transformer object.
Fit model to X and perform dimensionality reduction on X.
Training data.
Reduced version of X. This will always be a dense array.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Transform X back to its original space.
Returns an array X_original whose transform would be X.
New data.
Note that this is always a dense array.
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.
Estimator parameters.
Estimator instance.
Perform dimensionality reduction on X.
New data.
Reduced version of X. This will always be a dense array.
Hashing feature transformation using Totally Random Trees
Manifold learning on handwritten digits: Locally Linear Embedding, Isomap…
Column Transformer with Heterogeneous Data Sources
Clustering text documents using k-means


Fit model on training data X.
Training data.
Returns the transformer object.


Fit model to X and perform dimensionality reduction on X.
Training data.
Reduced version of X. This will always be a dense array.


Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.


Transform X back to its original space.
Returns an array X_original whose transform would be X.
New data.
Note that this is always a dense array.


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.
Estimator parameters.
Estimator instance.


Perform dimensionality reduction on X.
New data.
Reduced version of X. This will always be a dense array.


Linear Discriminant Analysis
A classifier with a linear decision boundary, generated by fitting class conditional densities to the data and using Bayes’ rule.
The model fits a Gaussian density to each class, assuming that all classes share the same covariance matrix.
The fitted model can also be used to reduce the dimensionality of the input by projecting it to the most discriminative directions, using the transform method.
New in version 0.17: LinearDiscriminantAnalysis.
Read more in the User Guide.
This should be left to None if covariance_estimator is used. Note that shrinkage works only with ‘lsqr’ and ‘eigen’ solvers.
The class prior probabilities. By default, the class proportions are inferred from the training data.
Number of components (<= min(n_classes - 1, n_features)) for dimensionality reduction. If None, will be set to min(n_classes - 1, n_features). This parameter only affects the transform method.
If True, explicitely compute the weighted within-class covariance matrix when solver is ‘svd’. The matrix is always computed and stored for the other solvers.
New in version 0.17.
Absolute threshold for a singular value of X to be considered significant, used to estimate the rank of X. Dimensions whose singular values are non-significant are discarded. Only used if solver is ‘svd’.
New in version 0.17.
If not None, covariance_estimator is used to estimate the covariance matrices instead of relying on the empirical covariance estimator (with potential shrinkage). The object should have a fit method and a covariance_ attribute like the estimators in sklearn.covariance. if None the shrinkage parameter drives the estimate.
This should be left to None if shrinkage is used. Note that covariance_estimator works only with ‘lsqr’ and ‘eigen’ solvers.
New in version 0.24.
Weight vector(s).
Intercept term.
Weighted within-class covariance matrix. It corresponds to sum_k prior_k * C_k where C_k is the covariance matrix of the samples in class k. The C_k are estimated using the (potentially shrunk) biased estimator of covariance. If solver is ‘svd’, only exists when store_covariance is True.
Percentage of variance explained by each of the selected components. If n_components is not set then all components are stored and the sum of explained variances is equal to 1.0. Only available when eigen or svd solver is used.
Class-wise means.
Class priors (sum to 1).
Scaling of the features in the space spanned by the class centroids. Only available for ‘svd’ and ‘eigen’ solvers.
Overall mean. Only present if solver is ‘svd’.
Unique class labels.
See also
Quadratic Discriminant Analysis.
decision_function(X)
Apply decision function to an array of samples.
fit(X, y)
Fit LinearDiscriminantAnalysis model according to the given
fit_transform(X[, y])
Fit to data, then transform it.
get_params([deep])
Get parameters for this estimator.
predict(X)
Predict class labels for samples in X.
predict_log_proba(X)
Estimate log probability.
predict_proba(X)
Estimate probability.
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.
transform(X)
Project data to maximize class separation.
Apply decision function to an array of samples.
The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. log p(y = k | x). In a binary classification setting this instead corresponds to the difference log p(y = 1 | x) - log p(y = 0 | x). See Mathematical formulation of the LDA and QDA classifiers.
Array of samples (test vectors).
Decision function values related to each class, per sample. In the two-class case, the shape is (n_samples,), giving the log likelihood ratio of the positive class.
training data and parameters.
Changed in version 0.19: store_covariance has been moved to main constructor.
Changed in version 0.19: tol has been moved to main constructor.
Training data.
Target values.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Predict class labels for samples in X.
Samples.
Predicted class label per sample.
Estimate log probability.
Input data.
Estimated log probabilities.
Estimate probability.
Input data.
Estimated probabilities.
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.
Test samples.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.
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.
Estimator parameters.
Estimator instance.
Project data to maximize class separation.
Input data.
Transformed data.


Linear Discriminant Analysis
A classifier with a linear decision boundary, generated by fitting class conditional densities to the data and using Bayes’ rule.
The model fits a Gaussian density to each class, assuming that all classes share the same covariance matrix.
The fitted model can also be used to reduce the dimensionality of the input by projecting it to the most discriminative directions, using the transform method.
New in version 0.17: LinearDiscriminantAnalysis.
Read more in the User Guide.
This should be left to None if covariance_estimator is used. Note that shrinkage works only with ‘lsqr’ and ‘eigen’ solvers.
The class prior probabilities. By default, the class proportions are inferred from the training data.
Number of components (<= min(n_classes - 1, n_features)) for dimensionality reduction. If None, will be set to min(n_classes - 1, n_features). This parameter only affects the transform method.
If True, explicitely compute the weighted within-class covariance matrix when solver is ‘svd’. The matrix is always computed and stored for the other solvers.
New in version 0.17.
Absolute threshold for a singular value of X to be considered significant, used to estimate the rank of X. Dimensions whose singular values are non-significant are discarded. Only used if solver is ‘svd’.
New in version 0.17.
If not None, covariance_estimator is used to estimate the covariance matrices instead of relying on the empirical covariance estimator (with potential shrinkage). The object should have a fit method and a covariance_ attribute like the estimators in sklearn.covariance. if None the shrinkage parameter drives the estimate.
This should be left to None if shrinkage is used. Note that covariance_estimator works only with ‘lsqr’ and ‘eigen’ solvers.
New in version 0.24.
Weight vector(s).
Intercept term.
Weighted within-class covariance matrix. It corresponds to sum_k prior_k * C_k where C_k is the covariance matrix of the samples in class k. The C_k are estimated using the (potentially shrunk) biased estimator of covariance. If solver is ‘svd’, only exists when store_covariance is True.
Percentage of variance explained by each of the selected components. If n_components is not set then all components are stored and the sum of explained variances is equal to 1.0. Only available when eigen or svd solver is used.
Class-wise means.
Class priors (sum to 1).
Scaling of the features in the space spanned by the class centroids. Only available for ‘svd’ and ‘eigen’ solvers.
Overall mean. Only present if solver is ‘svd’.
Unique class labels.
See also
Quadratic Discriminant Analysis.
decision_function(X)
Apply decision function to an array of samples.
fit(X, y)
Fit LinearDiscriminantAnalysis model according to the given
fit_transform(X[, y])
Fit to data, then transform it.
get_params([deep])
Get parameters for this estimator.
predict(X)
Predict class labels for samples in X.
predict_log_proba(X)
Estimate log probability.
predict_proba(X)
Estimate probability.
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.
transform(X)
Project data to maximize class separation.
Apply decision function to an array of samples.
The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. log p(y = k | x). In a binary classification setting this instead corresponds to the difference log p(y = 1 | x) - log p(y = 0 | x). See Mathematical formulation of the LDA and QDA classifiers.
Array of samples (test vectors).
Decision function values related to each class, per sample. In the two-class case, the shape is (n_samples,), giving the log likelihood ratio of the positive class.
training data and parameters.
Changed in version 0.19: store_covariance has been moved to main constructor.
Changed in version 0.19: tol has been moved to main constructor.
Training data.
Target values.
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Predict class labels for samples in X.
Samples.
Predicted class label per sample.
Estimate log probability.
Input data.
Estimated log probabilities.
Estimate probability.
Input data.
Estimated probabilities.
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.
Test samples.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.
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.
Estimator parameters.
Estimator instance.
Project data to maximize class separation.
Input data.
Transformed data.
Normal, Ledoit-Wolf and OAS Linear Discriminant Analysis for classification
Linear and Quadratic Discriminant Analysis with covariance ellipsoid
Comparison of LDA and PCA 2D projection of Iris dataset
Manifold learning on handwritten digits: Locally Linear Embedding, Isomap…
Dimensionality Reduction with Neighborhood Components Analysis


Apply decision function to an array of samples.
The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. log p(y = k | x). In a binary classification setting this instead corresponds to the difference log p(y = 1 | x) - log p(y = 0 | x). See Mathematical formulation of the LDA and QDA classifiers.
Array of samples (test vectors).
Decision function values related to each class, per sample. In the two-class case, the shape is (n_samples,), giving the log likelihood ratio of the positive class.


training data and parameters.
Changed in version 0.19: store_covariance has been moved to main constructor.
Changed in version 0.19: tol has been moved to main constructor.
Training data.
Target values.


Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Transformed array.


Predict class labels for samples in X.
Samples.
Predicted class label per sample.


Estimate log probability.
Input data.
Estimated log probabilities.


Estimate probability.
Input data.
Estimated probabilities.


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.
Test samples.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.


Project data to maximize class separation.
Input data.
Transformed data.


Quadratic Discriminant Analysis
A classifier with a quadratic decision boundary, generated by fitting class conditional densities to the data and using Bayes’ rule.
The model fits a Gaussian density to each class.
New in version 0.17: QuadraticDiscriminantAnalysis
Read more in the User Guide.
Class priors. By default, the class proportions are inferred from the training data.
Regularizes the per-class covariance estimates by transforming S2 as S2 = (1 - reg_param) * S2 + reg_param * np.eye(n_features), where S2 corresponds to the scaling_ attribute of a given class.
If True, the class covariance matrices are explicitely computed and stored in the self.covariance_ attribute.
New in version 0.17.
Absolute threshold for a singular value to be considered significant, used to estimate the rank of Xk where Xk is the centered matrix of samples in class k. This parameter does not affect the predictions. It only controls a warning that is raised when features are considered to be colinear.
New in version 0.17.
For each class, gives the covariance matrix estimated using the samples of that class. The estimations are unbiased. Only present if store_covariance is True.
Class-wise means.
Class priors (sum to 1).
For each class k an array of shape (n_features, n_k), where n_k = min(n_features, number of elements in class k) It is the rotation of the Gaussian distribution, i.e. its principal axis. It corresponds to V, the matrix of eigenvectors coming from the SVD of Xk = U S Vt where Xk is the centered matrix of samples from class k.
For each class, contains the scaling of the Gaussian distributions along its principal axes, i.e. the variance in the rotated coordinate system. It corresponds to S^2 /
(n_samples - 1), where S is the diagonal matrix of singular values from the SVD of Xk, where Xk is the centered matrix of samples from class k.
Unique class labels.
See also
Linear Discriminant Analysis.
decision_function(X)
Apply decision function to an array of samples.
fit(X, y)
Fit the model according to the given training data and parameters.
get_params([deep])
Get parameters for this estimator.
predict(X)
Perform classification on an array of test vectors X.
predict_log_proba(X)
Return log of posterior probabilities of classification.
predict_proba(X)
Return posterior probabilities of classification.
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.
Apply decision function to an array of samples.
The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. log p(y = k | x). In a binary classification setting this instead corresponds to the difference log p(y = 1 | x) - log p(y = 0 | x). See Mathematical formulation of the LDA and QDA classifiers.
Array of samples (test vectors).
Decision function values related to each class, per sample. In the two-class case, the shape is (n_samples,), giving the log likelihood ratio of the positive class.
Fit the model according to the given training data and parameters.
Changed in version 0.19: store_covariances has been moved to main constructor as store_covariance
Changed in version 0.19: tol has been moved to main constructor.
Training vector, where n_samples is the number of samples and n_features is the number of features.
Target values (integers)
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Perform classification on an array of test vectors X.
The predicted class C for each sample in X is returned.
Return log of posterior probabilities of classification.
Array of samples/test vectors.
Posterior log-probabilities of classification per class.
Return posterior probabilities of classification.
Array of samples/test vectors.
Posterior probabilities of classification per class.
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.
Test samples.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.
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.
Estimator parameters.
Estimator instance.


Quadratic Discriminant Analysis
A classifier with a quadratic decision boundary, generated by fitting class conditional densities to the data and using Bayes’ rule.
The model fits a Gaussian density to each class.
New in version 0.17: QuadraticDiscriminantAnalysis
Read more in the User Guide.
Class priors. By default, the class proportions are inferred from the training data.
Regularizes the per-class covariance estimates by transforming S2 as S2 = (1 - reg_param) * S2 + reg_param * np.eye(n_features), where S2 corresponds to the scaling_ attribute of a given class.
If True, the class covariance matrices are explicitely computed and stored in the self.covariance_ attribute.
New in version 0.17.
Absolute threshold for a singular value to be considered significant, used to estimate the rank of Xk where Xk is the centered matrix of samples in class k. This parameter does not affect the predictions. It only controls a warning that is raised when features are considered to be colinear.
New in version 0.17.
For each class, gives the covariance matrix estimated using the samples of that class. The estimations are unbiased. Only present if store_covariance is True.
Class-wise means.
Class priors (sum to 1).
For each class k an array of shape (n_features, n_k), where n_k = min(n_features, number of elements in class k) It is the rotation of the Gaussian distribution, i.e. its principal axis. It corresponds to V, the matrix of eigenvectors coming from the SVD of Xk = U S Vt where Xk is the centered matrix of samples from class k.
For each class, contains the scaling of the Gaussian distributions along its principal axes, i.e. the variance in the rotated coordinate system. It corresponds to S^2 /
(n_samples - 1), where S is the diagonal matrix of singular values from the SVD of Xk, where Xk is the centered matrix of samples from class k.
Unique class labels.
See also
Linear Discriminant Analysis.
decision_function(X)
Apply decision function to an array of samples.
fit(X, y)
Fit the model according to the given training data and parameters.
get_params([deep])
Get parameters for this estimator.
predict(X)
Perform classification on an array of test vectors X.
predict_log_proba(X)
Return log of posterior probabilities of classification.
predict_proba(X)
Return posterior probabilities of classification.
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.
Apply decision function to an array of samples.
The decision function is equal (up to a constant factor) to the log-posterior of the model, i.e. log p(y = k | x). In a binary classification setting this instead corresponds to the difference log p(y = 1 | x) - log p(y = 0 | x). See Mathematical formulation of the LDA and QDA classifiers.
Array of samples (test vectors).
Decision function values related to each class, per sample. In the two-class case, the shape is (n_samples,), giving the log likelihood ratio of the positive class.
Fit the model according to the given training data and parameters.
Changed in version 0.19: store_covariances has been moved to main constructor as store_covariance
Changed in version 0.19: tol has been moved to main constructor.
Training vector, where n_samples is the number of samples and n_features is the number of features.
Target values (integers)
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Perform classification on an array of test vectors X.
The predicted class C for each sample in X is returned.
Return log of posterior probabilities of classification.
Array of samples/test vectors.
Posterior log-probabilities of classification per class.
Return posterior probabilities of classification.
Array of samples/test vectors.
Posterior probabilities of classification per class.
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.
Test samples.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.
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.
Estimator parameters.
Estimator instance.
Classifier comparison
Linear and Quadratic Discriminant Analysis with covariance ellipsoid


Fit the model according to the given training data and parameters.
Changed in version 0.19: store_covariances has been moved to main constructor as store_covariance
Changed in version 0.19: tol has been moved to main constructor.
Training vector, where n_samples is the number of samples and n_features is the number of features.
Target values (integers)


Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.


Perform classification on an array of test vectors X.
The predicted class C for each sample in X is returned.


Return log of posterior probabilities of classification.
Array of samples/test vectors.
Posterior log-probabilities of classification per class.


Return posterior probabilities of classification.
Array of samples/test vectors.
Posterior probabilities of classification per class.


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.
Estimator parameters.
Estimator instance.


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.
Strategy to use to generate predictions.
“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.
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.
The explicit constant as predicted by the “constant” strategy. This parameter is useful only for the “constant” strategy.
Class labels for each output.
Number of label for each output.
Probability of each class for each output.
Number of outputs.
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.
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 the random classifier.
Training data.
Target values.
Sample weights.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Perform classification on test vectors X.
Test data.
Predicted target values for X.
Return log probability estimates for the test vectors X.
Training data, requires length = n_samples
Returns the log probability of the sample for each class in the model, where classes are ordered arithmetically for each output.
Return probability estimates for the test vectors X.
Test data.
Returns the probability of the sample for each class in the model, where classes are ordered arithmetically, for each output.
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.
Test samples. Passing None as test samples gives the same result as passing real test samples, since DummyClassifier operates independently of the sampled observations.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.
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.
Estimator parameters.
Estimator instance.


Fit the random classifier.
Training data.
Target values.
Sample weights.


Perform classification on test vectors X.
Test data.
Predicted target values for X.


Return log probability estimates for the test vectors X.
Training data, requires length = n_samples
Returns the log probability of the sample for each class in the model, where classes are ordered arithmetically for each output.


Return probability estimates for the test vectors X.
Test data.
Returns the probability of the sample for each class in the model, where classes are ordered arithmetically, for each output.


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.
Test samples. Passing None as test samples gives the same result as passing real test samples, since DummyClassifier operates independently of the sampled observations.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.


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.
Strategy to use to generate predictions.
The explicit constant as predicted by the “constant” strategy. This parameter is useful only for the “constant” strategy.
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.
Mean or median or quantile of the training targets or constant value given by the user.
Number of outputs.
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 the random regressor.
Training data.
Target values.
Sample weights.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Perform classification on test vectors X.
Test data.
Whether to return the standard deviation of posterior prediction. All zeros in this case.
New in version 0.20.
Predicted target values for X.
Standard deviation of predictive distribution of query points.
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.
Test samples. Passing None as test samples gives the same result as passing real test samples, since DummyRegressor operates independently of the sampled observations.
True values for X.
Sample weights.
R^2 of self.predict(X) wrt. y.
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.
Estimator parameters.
Estimator instance.


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.
Strategy to use to generate predictions.
The explicit constant as predicted by the “constant” strategy. This parameter is useful only for the “constant” strategy.
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.
Mean or median or quantile of the training targets or constant value given by the user.
Number of outputs.
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 the random regressor.
Training data.
Target values.
Sample weights.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Perform classification on test vectors X.
Test data.
Whether to return the standard deviation of posterior prediction. All zeros in this case.
New in version 0.20.
Predicted target values for X.
Standard deviation of predictive distribution of query points.
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.
Test samples. Passing None as test samples gives the same result as passing real test samples, since DummyRegressor operates independently of the sampled observations.
True values for X.
Sample weights.
R^2 of self.predict(X) wrt. y.
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.
Estimator parameters.
Estimator instance.
Poisson regression and non-normal loss


Fit the random regressor.
Training data.
Target values.
Sample weights.


Perform classification on test vectors X.
Test data.
Whether to return the standard deviation of posterior prediction. All zeros in this case.
New in version 0.20.
Predicted target values for X.
Standard deviation of predictive distribution of query points.


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.
Test samples. Passing None as test samples gives the same result as passing real test samples, since DummyRegressor operates independently of the sampled observations.
True values for X.
Sample weights.
R^2 of self.predict(X) wrt. y.


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.
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.
The maximum number of estimators at which boosting is terminated. In case of perfect fit, the learning procedure is stopped early.
Learning rate shrinks the contribution of each classifier by learning_rate. There is a trade-off between learning_rate and n_estimators.
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.
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.
The base estimator from which the ensemble is grown.
The collection of fitted sub-estimators.
The classes labels.
The number of classes.
Weights for each estimator in the boosted ensemble.
Classification error for each estimator in the boosted ensemble.
The impurity-based feature importances.
See also
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.
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.
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.
Y. Freund, R. Schapire, “A Decision-Theoretic Generalization of on-Line Learning and an Application to Boosting”, 1995.
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.
Compute the decision function of X.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
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.
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.
The feature importances.
Build a boosted classifier from the training set (X, y).
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The target values (class labels).
Sample weights. If None, the sample weights are initialized to 1 / n_samples.
Fitted estimator.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Predict classes for X.
The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The predicted classes.
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.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.
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.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.
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.
Test samples.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.
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.
Estimator parameters.
Estimator instance.
Compute decision function of X for each boosting iteration.
This method allows monitoring (i.e. determine error on testing set) after each boosting iteration.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
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.
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.
The input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The predicted classes.
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.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.
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.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
Labels for X.
Sample weights.


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.
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.
The maximum number of estimators at which boosting is terminated. In case of perfect fit, the learning procedure is stopped early.
Learning rate shrinks the contribution of each classifier by learning_rate. There is a trade-off between learning_rate and n_estimators.
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.
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.
The base estimator from which the ensemble is grown.
The collection of fitted sub-estimators.
The classes labels.
The number of classes.
Weights for each estimator in the boosted ensemble.
Classification error for each estimator in the boosted ensemble.
The impurity-based feature importances.
See also
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.
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.
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.
Y. Freund, R. Schapire, “A Decision-Theoretic Generalization of on-Line Learning and an Application to Boosting”, 1995.
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.
Compute the decision function of X.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
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.
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.
The feature importances.
Build a boosted classifier from the training set (X, y).
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The target values (class labels).
Sample weights. If None, the sample weights are initialized to 1 / n_samples.
Fitted estimator.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Predict classes for X.
The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The predicted classes.
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.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.
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.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.
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.
Test samples.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.
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.
Estimator parameters.
Estimator instance.
Compute decision function of X for each boosting iteration.
This method allows monitoring (i.e. determine error on testing set) after each boosting iteration.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
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.
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.
The input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The predicted classes.
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.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.
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.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
Labels for X.
Sample weights.
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


Compute the decision function of X.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
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.


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.
The feature importances.


Build a boosted classifier from the training set (X, y).
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The target values (class labels).
Sample weights. If None, the sample weights are initialized to 1 / n_samples.
Fitted estimator.


Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.


Predict classes for X.
The predicted class of an input sample is computed as the weighted mean prediction of the classifiers in the ensemble.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The predicted classes.


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.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.


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.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.


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.
Test samples.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.


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.
Estimator parameters.
Estimator instance.


Compute decision function of X for each boosting iteration.
This method allows monitoring (i.e. determine error on testing set) after each boosting iteration.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
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.


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.
The input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The predicted classes.


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.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The class probabilities of the input samples. The order of outputs is the same of that of the classes_ attribute.


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.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
Labels for X.
Sample weights.


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.
The base estimator from which the boosted ensemble is built. If None, then the base estimator is DecisionTreeRegressor initialized with max_depth=3.
The maximum number of estimators at which boosting is terminated. In case of perfect fit, the learning procedure is stopped early.
Learning rate shrinks the contribution of each regressor by learning_rate. There is a trade-off between learning_rate and n_estimators.
The loss function to use when updating the weights after each boosting iteration.
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.
The base estimator from which the ensemble is grown.
The collection of fitted sub-estimators.
Weights for each estimator in the boosted ensemble.
Regression error for each estimator in the boosted ensemble.
The impurity-based feature importances.
See also
Y. Freund, R. Schapire, “A Decision-Theoretic Generalization of on-Line Learning and an Application to Boosting”, 1995.
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.
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.
The feature importances.
Build a boosted regressor from the training set (X, y).
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The target values (real numbers).
Sample weights. If None, the sample weights are initialized to 1 / n_samples.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
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.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The predicted regression values.
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.
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.
True values for X.
Sample weights.
\(R^2\) of self.predict(X) wrt. y.
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 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.
Estimator parameters.
Estimator instance.
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.
The training input samples.
The predicted regression values.
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.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
Labels for X.
Sample weights.


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.
The base estimator from which the boosted ensemble is built. If None, then the base estimator is DecisionTreeRegressor initialized with max_depth=3.
The maximum number of estimators at which boosting is terminated. In case of perfect fit, the learning procedure is stopped early.
Learning rate shrinks the contribution of each regressor by learning_rate. There is a trade-off between learning_rate and n_estimators.
The loss function to use when updating the weights after each boosting iteration.
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.
The base estimator from which the ensemble is grown.
The collection of fitted sub-estimators.
Weights for each estimator in the boosted ensemble.
Regression error for each estimator in the boosted ensemble.
The impurity-based feature importances.
See also
Y. Freund, R. Schapire, “A Decision-Theoretic Generalization of on-Line Learning and an Application to Boosting”, 1995.
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.
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.
The feature importances.
Build a boosted regressor from the training set (X, y).
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The target values (real numbers).
Sample weights. If None, the sample weights are initialized to 1 / n_samples.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
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.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The predicted regression values.
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.
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.
True values for X.
Sample weights.
\(R^2\) of self.predict(X) wrt. y.
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 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.
Estimator parameters.
Estimator instance.
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.
The training input samples.
The predicted regression values.
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.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
Labels for X.
Sample weights.
Decision Tree Regression with AdaBoost


Build a boosted regressor from the training set (X, y).
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The target values (real numbers).
Sample weights. If None, the sample weights are initialized to 1 / n_samples.


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.
The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR.
The predicted regression values.


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.
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.
True values for X.
Sample weights.
\(R^2\) of self.predict(X) wrt. y.
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).


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.
The training input samples.
The predicted regression values.


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.
The base estimator to fit on random subsets of the dataset. If None, then the base estimator is a DecisionTreeClassifier.
The number of base estimators in the ensemble.
The number of samples to draw from X to train each base estimator (with replacement by default, see bootstrap for more details).
The number of features to draw from X to train each base estimator ( without replacement by default, see bootstrap_features for more details).
Whether samples are drawn with replacement. If False, sampling without replacement is performed.
Whether features are drawn with replacement.
Whether to use out-of-bag samples to estimate the generalization error.
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.
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.
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.
Controls the verbosity when fitting and predicting.
The base estimator from which the ensemble is grown.
The number of features when fit is performed.
The collection of fitted base estimators.
The subset of drawn samples for each base estimator.
The subset of drawn features for each base estimator.
The classes labels.
The number of classes.
Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when oob_score is True.
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.
L. Breiman, “Pasting small votes for classification in large databases and on-line”, Machine Learning, 36(1), 85-103, 1999.
L. Breiman, “Bagging predictors”, Machine Learning, 24(2), 123-140, 1996.
T. Ho, “The random subspace method for constructing decision forests”, Pattern Analysis and Machine Intelligence, 20(8), 832-844, 1998.
G. Louppe and P. Geurts, “Ensembles on Random Patches”, Machine Learning and Knowledge Discovery in Databases, 346-361, 2012.
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.
Average of the decision functions of the base classifiers.
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
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.
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.
set (X, y).
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
The target values (class labels in classification, real numbers in regression).
Sample weights. If None, then samples are equally weighted. Note that this is supported only if the base estimator supports sample weighting.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
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.
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
The predicted classes.
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.
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
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.
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
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.
Test samples.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.
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.
Estimator parameters.
Estimator instance.


Average of the decision functions of the base classifiers.
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
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.


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.


set (X, y).
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
The target values (class labels in classification, real numbers in regression).
Sample weights. If None, then samples are equally weighted. Note that this is supported only if the base estimator supports sample weighting.


Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.


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.
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
The predicted classes.


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.
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.


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.
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.


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.
Test samples.
True labels for X.
Sample weights.
Mean accuracy of self.predict(X) wrt. y.


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.
Estimator parameters.
Estimator instance.


A Bagging regressor.
A Bagging regressor is an ensemble meta-estimator that fits base regressors 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.
The base estimator to fit on random subsets of the dataset. If None, then the base estimator is a DecisionTreeRegressor.
The number of base estimators in the ensemble.
The number of samples to draw from X to train each base estimator (with replacement by default, see bootstrap for more details).
The number of features to draw from X to train each base estimator ( without replacement by default, see bootstrap_features for more details).
Whether samples are drawn with replacement. If False, sampling without replacement is performed.
Whether features are drawn with replacement.
Whether to use out-of-bag samples to estimate the generalization error.
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.
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.
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.
Controls the verbosity when fitting and predicting.
The base estimator from which the ensemble is grown.
The number of features when fit is performed.
The collection of fitted sub-estimators.
The subset of drawn samples for each base estimator.
The subset of drawn features for each base estimator.
Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when oob_score is True.
Prediction 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_prediction_ might contain NaN. This attribute exists only when oob_score is True.
L. Breiman, “Pasting small votes for classification in large databases and on-line”, Machine Learning, 36(1), 85-103, 1999.
L. Breiman, “Bagging predictors”, Machine Learning, 24(2), 123-140, 1996.
T. Ho, “The random subspace method for constructing decision forests”, Pattern Analysis and Machine Intelligence, 20(8), 832-844, 1998.
G. Louppe and P. Geurts, “Ensembles on Random Patches”, Machine Learning and Knowledge Discovery in Databases, 346-361, 2012.
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 regression target 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.
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.
set (X, y).
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
The target values (class labels in classification, real numbers in regression).
Sample weights. If None, then samples are equally weighted. Note that this is supported only if the base estimator supports sample weighting.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Predict regression target for X.
The predicted regression target of an input sample is computed as the mean predicted regression targets of the estimators in the ensemble.
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
The predicted values.
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.
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.
True values for X.
Sample weights.
\(R^2\) of self.predict(X) wrt. y.
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 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.
Estimator parameters.
Estimator instance.


A Bagging regressor.
A Bagging regressor is an ensemble meta-estimator that fits base regressors 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.
The base estimator to fit on random subsets of the dataset. If None, then the base estimator is a DecisionTreeRegressor.
The number of base estimators in the ensemble.
The number of samples to draw from X to train each base estimator (with replacement by default, see bootstrap for more details).
The number of features to draw from X to train each base estimator ( without replacement by default, see bootstrap_features for more details).
Whether samples are drawn with replacement. If False, sampling without replacement is performed.
Whether features are drawn with replacement.
Whether to use out-of-bag samples to estimate the generalization error.
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.
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.
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.
Controls the verbosity when fitting and predicting.
The base estimator from which the ensemble is grown.
The number of features when fit is performed.
The collection of fitted sub-estimators.
The subset of drawn samples for each base estimator.
The subset of drawn features for each base estimator.
Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when oob_score is True.
Prediction 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_prediction_ might contain NaN. This attribute exists only when oob_score is True.
L. Breiman, “Pasting small votes for classification in large databases and on-line”, Machine Learning, 36(1), 85-103, 1999.
L. Breiman, “Bagging predictors”, Machine Learning, 24(2), 123-140, 1996.
T. Ho, “The random subspace method for constructing decision forests”, Pattern Analysis and Machine Intelligence, 20(8), 832-844, 1998.
G. Louppe and P. Geurts, “Ensembles on Random Patches”, Machine Learning and Knowledge Discovery in Databases, 346-361, 2012.
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 regression target 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.
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.
set (X, y).
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
The target values (class labels in classification, real numbers in regression).
Sample weights. If None, then samples are equally weighted. Note that this is supported only if the base estimator supports sample weighting.
Get parameters for this estimator.
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Parameter names mapped to their values.
Predict regression target for X.
The predicted regression target of an input sample is computed as the mean predicted regression targets of the estimators in the ensemble.
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
The predicted values.
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.
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.
True values for X.
Sample weights.
\(R^2\) of self.predict(X) wrt. y.
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 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.
Estimator parameters.
Estimator instance.
Single estimator versus bagging: bias-variance decomposition


Predict regression target for X.
The predicted regression target of an input sample is computed as the mean predicted regression targets of the estimators in the ensemble.
The training input samples. Sparse matrices are accepted only if they are supported by the base estimator.
The predicted values.