This class implements a meta estimator that fits a number of
randomized decision trees (a.k.a. extra-trees) on various sub-samples
of the dataset and uses averaging to improve the predictive accuracy
and control over-fitting.
Read more in the User Guide.
Parameters:
n_estimators (int, default=100) –
The number of trees in the forest.
Changed in version 0.22: The default value of n_estimators changed from 10 to 100
in 0.22.
The function to measure the quality of a split. Supported criteria
are “squared_error” for the mean squared error, which is equal to
variance reduction as feature selection criterion, and “absolute_error”
for the mean absolute error.
New in version 0.18: Mean Absolute Error (MAE) criterion.
Deprecated since version 1.0: Criterion “mse” was deprecated in v1.0 and will be removed in
version 1.2. Use criterion=”squared_error” which is equivalent.
Deprecated since version 1.0: Criterion “mae” was deprecated in v1.0 and will be removed in
version 1.2. Use criterion=”absolute_error” which is equivalent.
max_depth (int, default=None) – The maximum depth of the tree. If None, then nodes are expanded until
all leaves are pure or until all leaves contain less than
min_samples_split samples.
min_samples_split (int or float, default=2) –
The minimum number of samples required to split an internal node:
If int, then consider min_samples_split as the minimum number.
If float, then min_samples_split is a fraction and
ceil(min_samples_split * n_samples) are the minimum
number of samples for each split.
Changed in version 0.18: Added float values for fractions.
min_samples_leaf (int or float, default=1) –
The minimum number of samples required to be at a leaf node.
A split point at any depth will only be considered if it leaves at
least min_samples_leaf training samples in each of the left and
right branches. This may have the effect of smoothing the model,
especially in regression.
If int, then consider min_samples_leaf as the minimum number.
If float, then min_samples_leaf is a fraction and
ceil(min_samples_leaf * n_samples) are the minimum
number of samples for each node.
Changed in version 0.18: Added float values for fractions.
min_weight_fraction_leaf (float, default=0.0) – The minimum weighted fraction of the sum total of weights (of all
the input samples) required to be at a leaf node. Samples have
equal weight when sample_weight is not provided.
max_features ({"sqrt", "log2", None}, int or float, default=None) –
The number of features to consider when looking for the best split:
If int, then consider max_features features at each split.
If float, then max_features is a fraction and
round(max_features * n_features) features are considered at each
split.
If “auto”, then max_features=n_features.
If “sqrt”, then max_features=sqrt(n_features).
If “log2”, then max_features=log2(n_features).
If None or 1.0, then max_features=n_features.
Note
The default of 1.0 is equivalent to bagged trees and more
randomness can be achieved by setting smaller values, e.g. 0.3.
Changed in version 1.1: The default of max_features changed from “auto” to 1.0.
Deprecated since version 1.1: The “auto” option was deprecated in 1.1 and will be removed
in 1.3.
Note: the search for a split does not stop until at least one
valid partition of the node samples is found, even if it requires to
effectively inspect more than max_features features.
max_leaf_nodes (int, default=None) – Grow trees with max_leaf_nodes in best-first fashion.
Best nodes are defined as relative reduction in impurity.
If None then unlimited number of leaf nodes.
min_impurity_decrease (float, default=0.0) –
A node will be split if this split induces a decrease of the impurity
greater than or equal to this value.
The weighted impurity decrease equation is the following:
where N is the total number of samples, N_t is the number of
samples at the current node, N_t_L is the number of samples in the
left child, and N_t_R is the number of samples in the right child.
N, N_t, N_t_R and N_t_L all refer to the weighted sum,
if sample_weight is passed.
New in version 0.19.
bootstrap (bool, default=False) – Whether bootstrap samples are used when building trees. If False, the
whole dataset is used to build each tree.
oob_score (bool, default=False) – Whether to use out-of-bag samples to estimate the generalization score.
Only available if bootstrap=True.
n_jobs (int, default=None) – The number of jobs to run in parallel. fit(), predict(),
decision_path() and apply() are all parallelized over the
trees. None means 1 unless in a joblib.parallel_backend
context. -1 means using all processors. See Glossary for more details.
random_state (int, RandomState instance or None, default=None) –
Controls 3 sources of randomness:
the bootstrapping of the samples used when building trees
(if bootstrap=True)
the sampling of the features to consider when looking for the best
split at each node (if max_features<n_features)
the draw of the splits for each of the max_features
See Glossary for details.
verbose (int, default=0) – Controls the verbosity when fitting and predicting.
warm_start (bool, default=False) – When set to True, reuse the solution of the previous call to fit
and add more estimators to the ensemble, otherwise, just fit a whole
new forest. See the Glossary.
ccp_alpha (non-negative float, default=0.0) –
Complexity parameter used for Minimal Cost-Complexity Pruning. The
subtree with the largest cost complexity that is smaller than
ccp_alpha will be chosen. By default, no pruning is performed. See
minimal_cost_complexity_pruning for details.
New in version 0.22.
max_samples (int or float, default=None) –
If bootstrap is True, the number of samples to draw from X
to train each base estimator.
If None (default), then draw X.shape[0] samples.
If int, then draw max_samples samples.
If float, then draw max_samples * X.shape[0] samples. Thus,
max_samples should be in the interval (0.0, 1.0].
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.
Prediction computed with out-of-bag estimate on the training set.
This attribute exists only when oob_score is True.
Type:
ndarray of shape (n_samples,) or (n_samples, n_outputs)
See also
ExtraTreesClassifier
An extra-trees classifier with random splits.
RandomForestClassifier
A random forest classifier with optimal splits.
RandomForestRegressor
Ensemble regressor using trees with optimal splits.
Notes
The default values for the parameters controlling the size of the trees
(e.g. max_depth, min_samples_leaf, etc.) lead to fully grown and
unpruned trees which can potentially be very large on some data sets. To
reduce memory consumption, the complexity and size of the trees should be
controlled by setting those parameter values.
This algorithm builds an additive model in a forward stage-wise fashion; it
allows for the optimization of arbitrary differentiable loss functions. In
each stage n_classes_ regression trees are fit on the negative gradient
of the loss function, e.g. binary or multiclass log loss. Binary
classification is a special case where only a single regression tree is
induced.
sklearn.ensemble.HistGradientBoostingClassifier is a much faster
variant of this algorithm for intermediate datasets (n_samples >= 10_000).
Read more in the User Guide.
Parameters:
loss ({'log_loss', 'deviance', 'exponential'}, default='log_loss') –
The loss function to be optimized. ‘log_loss’ refers to binomial and
multinomial deviance, the same as used in logistic regression.
It is a good choice for classification with probabilistic outputs.
For loss ‘exponential’, gradient boosting recovers the AdaBoost algorithm.
Deprecated since version 1.1: The loss ‘deviance’ was deprecated in v1.1 and will be removed in
version 1.3. Use loss=’log_loss’ which is equivalent.
learning_rate (float, default=0.1) – Learning rate shrinks the contribution of each tree by learning_rate.
There is a trade-off between learning_rate and n_estimators.
Values must be in the range [0.0, inf).
n_estimators (int, default=100) – The number of boosting stages to perform. Gradient boosting
is fairly robust to over-fitting so a large number usually
results in better performance.
Values must be in the range [1, inf).
subsample (float, default=1.0) – The fraction of samples to be used for fitting the individual base
learners. If smaller than 1.0 this results in Stochastic Gradient
Boosting. subsample interacts with the parameter n_estimators.
Choosing subsample < 1.0 leads to a reduction of variance
and an increase in bias.
Values must be in the range (0.0, 1.0].
The function to measure the quality of a split. Supported criteria are
‘friedman_mse’ for the mean squared error with improvement score by
Friedman, ‘squared_error’ for mean squared error. The default value of
‘friedman_mse’ is generally the best as it can provide a better
approximation in some cases.
New in version 0.18.
min_samples_split (int or float, default=2) –
The minimum number of samples required to split an internal node:
If int, values must be in the range [2, inf).
If float, values must be in the range (0.0, 1.0] and min_samples_split
will be ceil(min_samples_split * n_samples).
Changed in version 0.18: Added float values for fractions.
min_samples_leaf (int or float, default=1) –
The minimum number of samples required to be at a leaf node.
A split point at any depth will only be considered if it leaves at
least min_samples_leaf training samples in each of the left and
right branches. This may have the effect of smoothing the model,
especially in regression.
If int, values must be in the range [1, inf).
If float, values must be in the range (0.0, 1.0) and min_samples_leaf
will be ceil(min_samples_leaf * n_samples).
Changed in version 0.18: Added float values for fractions.
min_weight_fraction_leaf (float, default=0.0) – The minimum weighted fraction of the sum total of weights (of all
the input samples) required to be at a leaf node. Samples have
equal weight when sample_weight is not provided.
Values must be in the range [0.0, 0.5].
max_depth (int or None, default=3) – Maximum depth of the individual regression estimators. The maximum
depth limits the number of nodes in the tree. Tune this parameter
for best performance; the best value depends on the interaction
of the input variables. If None, then nodes are expanded until
all leaves are pure or until all leaves contain less than
min_samples_split samples.
If int, values must be in the range [1, inf).
min_impurity_decrease (float, default=0.0) –
A node will be split if this split induces a decrease of the impurity
greater than or equal to this value.
Values must be in the range [0.0, inf).
The weighted impurity decrease equation is the following:
where N is the total number of samples, N_t is the number of
samples at the current node, N_t_L is the number of samples in the
left child, and N_t_R is the number of samples in the right child.
N, N_t, N_t_R and N_t_L all refer to the weighted sum,
if sample_weight is passed.
New in version 0.19.
init (estimator or 'zero', default=None) – An estimator object that is used to compute the initial predictions.
init has to provide fit() and predict_proba(). If
‘zero’, the initial raw predictions are set to zero. By default, a
DummyEstimator predicting the classes priors is used.
random_state (int, RandomState instance or None, default=None) – Controls the random seed given to each Tree estimator at each
boosting iteration.
In addition, it controls the random permutation of the features at
each split (see Notes for more details).
It also controls the random splitting of the training data to obtain a
validation set if n_iter_no_change is not None.
Pass an int for reproducible output across multiple function calls.
See Glossary.
max_features ({'auto', 'sqrt', 'log2'}, int or float, default=None) –
The number of features to consider when looking for the best split:
If int, values must be in the range [1, inf).
If float, values must be in the range (0.0, 1.0] and the features
considered at each split will be max(1, int(max_features * n_features_in_)).
If ‘auto’, then max_features=sqrt(n_features).
If ‘sqrt’, then max_features=sqrt(n_features).
If ‘log2’, then max_features=log2(n_features).
If None, then max_features=n_features.
Choosing max_features < n_features leads to a reduction of variance
and an increase in bias.
Note: the search for a split does not stop until at least one
valid partition of the node samples is found, even if it requires to
effectively inspect more than max_features features.
verbose (int, default=0) – Enable verbose output. If 1 then it prints progress and performance
once in a while (the more trees the lower the frequency). If greater
than 1 then it prints progress and performance for every tree.
Values must be in the range [0, inf).
max_leaf_nodes (int, default=None) – Grow trees with max_leaf_nodes in best-first fashion.
Best nodes are defined as relative reduction in impurity.
Values must be in the range [2, inf).
If None, then unlimited number of leaf nodes.
warm_start (bool, default=False) – When set to True, reuse the solution of the previous call to fit
and add more estimators to the ensemble, otherwise, just erase the
previous solution. See the Glossary.
validation_fraction (float, default=0.1) –
The proportion of training data to set aside as validation set for
early stopping. Values must be in the range (0.0, 1.0).
Only used if n_iter_no_change is set to an integer.
New in version 0.20.
n_iter_no_change (int, default=None) –
n_iter_no_change is used to decide if early stopping will be used
to terminate training when validation score is not improving. By
default it is set to None to disable early stopping. If set to a
number, it will set aside validation_fraction size of the training
data as validation and terminate training when validation score is not
improving in all of the previous n_iter_no_change numbers of
iterations. The split is stratified.
Values must be in the range [1, inf).
New in version 0.20.
tol (float, default=1e-4) –
Tolerance for the early stopping. When the loss is not improving
by at least tol for n_iter_no_change iterations (if set to a
number), the training stops.
Values must be in the range [0.0, inf).
New in version 0.20.
ccp_alpha (non-negative float, default=0.0) –
Complexity parameter used for Minimal Cost-Complexity Pruning. The
subtree with the largest cost complexity that is smaller than
ccp_alpha will be chosen. By default, no pruning is performed.
Values must be in the range [0.0, inf).
See minimal_cost_complexity_pruning for details.
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 improvement in loss (= deviance) on the out-of-bag samples
relative to the previous iteration.
oob_improvement_[0] is the improvement in
loss of the first stage over the init estimator.
Only available if subsample<1.0
The i-th score train_score_[i] is the deviance (= loss) of the
model at iteration i on the in-bag sample.
If subsample==1 this is the deviance on the training data.
A meta-estimator that fits a number of decision tree classifiers on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting.
AdaBoostClassifier
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 where the weights of incorrectly classified instances are adjusted such that subsequent classifiers focus more on difficult cases.
Notes
The features are always randomly permuted at each split. Therefore,
the best found split may vary, even with the same training data and
max_features=n_features, if the improvement of the criterion is
identical for several splits enumerated during the search of the best
split. To obtain a deterministic behaviour during fitting,
random_state has to be fixed.
References
J. Friedman, Greedy Function Approximation: A Gradient Boosting
Machine, The Annals of Statistics, Vol. 29, No. 5, 2001.
Friedman, Stochastic Gradient Boosting, 1999
T. Hastie, R. Tibshirani and J. Friedman.
Elements of Statistical Learning Ed. 2, Springer, 2009.
Examples
The following example shows how to fit a gradient boosting classifier with
100 decision stumps as weak learners.
X ({array-like, sparse matrix} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to
dtype=np.float32 and if a sparse matrix is provided
to a sparse csr_matrix.
Returns:
score – The decision function of the input samples, which corresponds to
the raw values predicted from the trees of the ensemble . The
order of the classes corresponds to that in the attribute
classes_. Regression and binary classification produce an
array of shape (n_samples,).
Return type:
ndarray of shape (n_samples, n_classes) or (n_samples,)
X ({array-like, sparse matrix} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to
dtype=np.float32 and if a sparse matrix is provided
to a sparse csr_matrix.
X ({array-like, sparse matrix} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to
dtype=np.float32 and if a sparse matrix is provided
to a sparse csr_matrix.
Returns:
p – The class log-probabilities of the input samples. The order of the
classes corresponds to that in the attribute classes_.
Return type:
ndarray of shape (n_samples, n_classes)
Raises:
AttributeError – If the loss does not support probabilities.
X ({array-like, sparse matrix} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to
dtype=np.float32 and if a sparse matrix is provided
to a sparse csr_matrix.
Returns:
p – The class probabilities of the input samples. The order of the
classes corresponds to that in the attribute classes_.
Return type:
ndarray of shape (n_samples, n_classes)
Raises:
AttributeError – If the loss does not support probabilities.
Compute decision function of X for each iteration.
This method allows monitoring (i.e. determine error on testing set)
after each stage.
Parameters:
X ({array-like, sparse matrix} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to
dtype=np.float32 and if a sparse matrix is provided
to a sparse csr_matrix.
Yields:
score (generator of ndarray of shape (n_samples, k)) – The decision function of the input samples, which corresponds to
the raw values predicted from the trees of the ensemble . The
classes corresponds to that in the attribute classes_.
Regression and binary classification are special cases with
k==1, otherwise k==n_classes.
This method allows monitoring (i.e. determine error on testing set)
after each stage.
Parameters:
X ({array-like, sparse matrix} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to
dtype=np.float32 and if a sparse matrix is provided
to a sparse csr_matrix.
Yields:
y (generator of ndarray of shape (n_samples,)) – The predicted value of the input samples.
This method allows monitoring (i.e. determine error on testing set)
after each stage.
Parameters:
X ({array-like, sparse matrix} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to
dtype=np.float32 and if a sparse matrix is provided
to a sparse csr_matrix.
Yields:
y (generator of ndarray of shape (n_samples,)) – The predicted value of the input samples.
This estimator builds an additive model in a forward stage-wise fashion; it
allows for the optimization of arbitrary differentiable loss functions. In
each stage a regression tree is fit on the negative gradient of the given
loss function.
sklearn.ensemble.HistGradientBoostingRegressor is a much faster
variant of this algorithm for intermediate datasets (n_samples >= 10_000).
Read more in the User Guide.
Parameters:
loss ({'squared_error', 'absolute_error', 'huber', 'quantile'}, default='squared_error') – Loss function to be optimized. ‘squared_error’ refers to the squared
error for regression. ‘absolute_error’ refers to the absolute error of
regression and is a robust loss function. ‘huber’ is a
combination of the two. ‘quantile’ allows quantile regression (use
alpha to specify the quantile).
learning_rate (float, default=0.1) – Learning rate shrinks the contribution of each tree by learning_rate.
There is a trade-off between learning_rate and n_estimators.
Values must be in the range [0.0, inf).
n_estimators (int, default=100) – The number of boosting stages to perform. Gradient boosting
is fairly robust to over-fitting so a large number usually
results in better performance.
Values must be in the range [1, inf).
subsample (float, default=1.0) – The fraction of samples to be used for fitting the individual base
learners. If smaller than 1.0 this results in Stochastic Gradient
Boosting. subsample interacts with the parameter n_estimators.
Choosing subsample < 1.0 leads to a reduction of variance
and an increase in bias.
Values must be in the range (0.0, 1.0].
The function to measure the quality of a split. Supported criteria are
“friedman_mse” for the mean squared error with improvement score by
Friedman, “squared_error” for mean squared error. The default value of
“friedman_mse” is generally the best as it can provide a better
approximation in some cases.
New in version 0.18.
min_samples_split (int or float, default=2) –
The minimum number of samples required to split an internal node:
If int, values must be in the range [2, inf).
If float, values must be in the range (0.0, 1.0] and min_samples_split
will be ceil(min_samples_split * n_samples).
Changed in version 0.18: Added float values for fractions.
min_samples_leaf (int or float, default=1) –
The minimum number of samples required to be at a leaf node.
A split point at any depth will only be considered if it leaves at
least min_samples_leaf training samples in each of the left and
right branches. This may have the effect of smoothing the model,
especially in regression.
If int, values must be in the range [1, inf).
If float, values must be in the range (0.0, 1.0) and min_samples_leaf
will be ceil(min_samples_leaf * n_samples).
Changed in version 0.18: Added float values for fractions.
min_weight_fraction_leaf (float, default=0.0) – The minimum weighted fraction of the sum total of weights (of all
the input samples) required to be at a leaf node. Samples have
equal weight when sample_weight is not provided.
Values must be in the range [0.0, 0.5].
max_depth (int or None, default=3) – Maximum depth of the individual regression estimators. The maximum
depth limits the number of nodes in the tree. Tune this parameter
for best performance; the best value depends on the interaction
of the input variables. If None, then nodes are expanded until
all leaves are pure or until all leaves contain less than
min_samples_split samples.
If int, values must be in the range [1, inf).
min_impurity_decrease (float, default=0.0) –
A node will be split if this split induces a decrease of the impurity
greater than or equal to this value.
Values must be in the range [0.0, inf).
The weighted impurity decrease equation is the following:
where N is the total number of samples, N_t is the number of
samples at the current node, N_t_L is the number of samples in the
left child, and N_t_R is the number of samples in the right child.
N, N_t, N_t_R and N_t_L all refer to the weighted sum,
if sample_weight is passed.
New in version 0.19.
init (estimator or 'zero', default=None) – An estimator object that is used to compute the initial predictions.
init has to provide fit and predict. If ‘zero’, the
initial raw predictions are set to zero. By default a
DummyEstimator is used, predicting either the average target value
(for loss=’squared_error’), or a quantile for the other losses.
random_state (int, RandomState instance or None, default=None) – Controls the random seed given to each Tree estimator at each
boosting iteration.
In addition, it controls the random permutation of the features at
each split (see Notes for more details).
It also controls the random splitting of the training data to obtain a
validation set if n_iter_no_change is not None.
Pass an int for reproducible output across multiple function calls.
See Glossary.
max_features ({'auto', 'sqrt', 'log2'}, int or float, default=None) –
The number of features to consider when looking for the best split:
If int, values must be in the range [1, inf).
If float, values must be in the range (0.0, 1.0] and the features
considered at each split will be max(1, int(max_features * n_features_in_)).
If “auto”, then max_features=n_features.
If “sqrt”, then max_features=sqrt(n_features).
If “log2”, then max_features=log2(n_features).
If None, then max_features=n_features.
Choosing max_features < n_features leads to a reduction of variance
and an increase in bias.
Note: the search for a split does not stop until at least one
valid partition of the node samples is found, even if it requires to
effectively inspect more than max_features features.
alpha (float, default=0.9) – The alpha-quantile of the huber loss function and the quantile
loss function. Only if loss='huber' or loss='quantile'.
Values must be in the range (0.0, 1.0).
verbose (int, default=0) – Enable verbose output. If 1 then it prints progress and performance
once in a while (the more trees the lower the frequency). If greater
than 1 then it prints progress and performance for every tree.
Values must be in the range [0, inf).
max_leaf_nodes (int, default=None) – Grow trees with max_leaf_nodes in best-first fashion.
Best nodes are defined as relative reduction in impurity.
Values must be in the range [2, inf).
If None, then unlimited number of leaf nodes.
warm_start (bool, default=False) – When set to True, reuse the solution of the previous call to fit
and add more estimators to the ensemble, otherwise, just erase the
previous solution. See the Glossary.
validation_fraction (float, default=0.1) –
The proportion of training data to set aside as validation set for
early stopping. Values must be in the range (0.0, 1.0).
Only used if n_iter_no_change is set to an integer.
New in version 0.20.
n_iter_no_change (int, default=None) –
n_iter_no_change is used to decide if early stopping will be used
to terminate training when validation score is not improving. By
default it is set to None to disable early stopping. If set to a
number, it will set aside validation_fraction size of the training
data as validation and terminate training when validation score is not
improving in all of the previous n_iter_no_change numbers of
iterations.
Values must be in the range [1, inf).
New in version 0.20.
tol (float, default=1e-4) –
Tolerance for the early stopping. When the loss is not improving
by at least tol for n_iter_no_change iterations (if set to a
number), the training stops.
Values must be in the range [0.0, inf).
New in version 0.20.
ccp_alpha (non-negative float, default=0.0) –
Complexity parameter used for Minimal Cost-Complexity Pruning. The
subtree with the largest cost complexity that is smaller than
ccp_alpha will be chosen. By default, no pruning is performed.
Values must be in the range [0.0, inf).
See minimal_cost_complexity_pruning for details.
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 improvement in loss (= deviance) on the out-of-bag samples
relative to the previous iteration.
oob_improvement_[0] is the improvement in
loss of the first stage over the init estimator.
Only available if subsample<1.0
The i-th score train_score_[i] is the deviance (= loss) of the
model at iteration i on the in-bag sample.
If subsample==1 this is the deviance on the training data.
The features are always randomly permuted at each split. Therefore,
the best found split may vary, even with the same training data and
max_features=n_features, if the improvement of the criterion is
identical for several splits enumerated during the search of the best
split. To obtain a deterministic behaviour during fitting,
random_state has to be fixed.
References
J. Friedman, Greedy Function Approximation: A Gradient Boosting
Machine, The Annals of Statistics, Vol. 29, No. 5, 2001.
Friedman, Stochastic Gradient Boosting, 1999
T. Hastie, R. Tibshirani and J. Friedman.
Elements of Statistical Learning Ed. 2, Springer, 2009.
Apply trees in the ensemble to X, return leaf indices.
New in version 0.17.
Parameters:
X ({array-like, sparse matrix} of shape (n_samples, n_features)) – The input samples. Internally, its dtype will be converted to
dtype=np.float32. If a sparse matrix is provided, it will
be converted to a sparse csr_matrix.
Returns:
X_leaves – For each datapoint x in X and for each tree in the ensemble,
return the index of the leaf x ends up in each estimator.
X ({array-like, sparse matrix} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to
dtype=np.float32 and if a sparse matrix is provided
to a sparse csr_matrix.
This method allows monitoring (i.e. determine error on testing set)
after each stage.
Parameters:
X ({array-like, sparse matrix} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to
dtype=np.float32 and if a sparse matrix is provided
to a sparse csr_matrix.
Yields:
y (generator of ndarray of shape (n_samples,)) – The predicted value of the input samples.
A random forest is a meta estimator that fits a number of classifying
decision trees on various sub-samples of the dataset and uses averaging
to improve the predictive accuracy and control over-fitting.
The sub-sample size is controlled with the max_samples parameter if
bootstrap=True (default), otherwise the whole dataset is used to build
each tree.
Read more in the User Guide.
Parameters:
n_estimators (int, default=100) –
The number of trees in the forest.
Changed in version 0.22: The default value of n_estimators changed from 10 to 100
in 0.22.
The function to measure the quality of a split. Supported criteria
are “squared_error” for the mean squared error, which is equal to
variance reduction as feature selection criterion, “absolute_error”
for the mean absolute error, and “poisson” which uses reduction in
Poisson deviance to find splits.
Training using “absolute_error” is significantly slower
than when using “squared_error”.
New in version 0.18: Mean Absolute Error (MAE) criterion.
New in version 1.0: Poisson criterion.
Deprecated since version 1.0: Criterion “mse” was deprecated in v1.0 and will be removed in
version 1.2. Use criterion=”squared_error” which is equivalent.
Deprecated since version 1.0: Criterion “mae” was deprecated in v1.0 and will be removed in
version 1.2. Use criterion=”absolute_error” which is equivalent.
max_depth (int, default=None) – The maximum depth of the tree. If None, then nodes are expanded until
all leaves are pure or until all leaves contain less than
min_samples_split samples.
min_samples_split (int or float, default=2) –
The minimum number of samples required to split an internal node:
If int, then consider min_samples_split as the minimum number.
If float, then min_samples_split is a fraction and
ceil(min_samples_split * n_samples) are the minimum
number of samples for each split.
Changed in version 0.18: Added float values for fractions.
min_samples_leaf (int or float, default=1) –
The minimum number of samples required to be at a leaf node.
A split point at any depth will only be considered if it leaves at
least min_samples_leaf training samples in each of the left and
right branches. This may have the effect of smoothing the model,
especially in regression.
If int, then consider min_samples_leaf as the minimum number.
If float, then min_samples_leaf is a fraction and
ceil(min_samples_leaf * n_samples) are the minimum
number of samples for each node.
Changed in version 0.18: Added float values for fractions.
min_weight_fraction_leaf (float, default=0.0) – The minimum weighted fraction of the sum total of weights (of all
the input samples) required to be at a leaf node. Samples have
equal weight when sample_weight is not provided.
max_features ({"sqrt", "log2", None}, int or float, default=None) –
The number of features to consider when looking for the best split:
If int, then consider max_features features at each split.
If float, then max_features is a fraction and
round(max_features * n_features) features are considered at each
split.
If “auto”, then max_features=n_features.
If “sqrt”, then max_features=sqrt(n_features).
If “log2”, then max_features=log2(n_features).
If None or 1.0, then max_features=n_features.
Note
The default of 1.0 is equivalent to bagged trees and more
randomness can be achieved by setting smaller values, e.g. 0.3.
Changed in version 1.1: The default of max_features changed from “auto” to 1.0.
Deprecated since version 1.1: The “auto” option was deprecated in 1.1 and will be removed
in 1.3.
Note: the search for a split does not stop until at least one
valid partition of the node samples is found, even if it requires to
effectively inspect more than max_features features.
max_leaf_nodes (int, default=None) – Grow trees with max_leaf_nodes in best-first fashion.
Best nodes are defined as relative reduction in impurity.
If None then unlimited number of leaf nodes.
min_impurity_decrease (float, default=0.0) –
A node will be split if this split induces a decrease of the impurity
greater than or equal to this value.
The weighted impurity decrease equation is the following:
where N is the total number of samples, N_t is the number of
samples at the current node, N_t_L is the number of samples in the
left child, and N_t_R is the number of samples in the right child.
N, N_t, N_t_R and N_t_L all refer to the weighted sum,
if sample_weight is passed.
New in version 0.19.
bootstrap (bool, default=True) – Whether bootstrap samples are used when building trees. If False, the
whole dataset is used to build each tree.
oob_score (bool, default=False) – Whether to use out-of-bag samples to estimate the generalization score.
Only available if bootstrap=True.
n_jobs (int, default=None) – The number of jobs to run in parallel. fit(), predict(),
decision_path() and apply() are all parallelized over the
trees. None means 1 unless in a joblib.parallel_backend
context. -1 means using all processors. See Glossary for more details.
random_state (int, RandomState instance or None, default=None) – Controls both the randomness of the bootstrapping of the samples used
when building trees (if bootstrap=True) and the sampling of the
features to consider when looking for the best split at each node
(if max_features<n_features).
See Glossary for details.
verbose (int, default=0) – Controls the verbosity when fitting and predicting.
warm_start (bool, default=False) – When set to True, reuse the solution of the previous call to fit
and add more estimators to the ensemble, otherwise, just fit a whole
new forest. See the Glossary.
ccp_alpha (non-negative float, default=0.0) –
Complexity parameter used for Minimal Cost-Complexity Pruning. The
subtree with the largest cost complexity that is smaller than
ccp_alpha will be chosen. By default, no pruning is performed. See
minimal_cost_complexity_pruning for details.
New in version 0.22.
max_samples (int or float, default=None) –
If bootstrap is True, the number of samples to draw from X
to train each base estimator.
If None (default), then draw X.shape[0] samples.
If int, then draw max_samples samples.
If float, then draw max_samples * X.shape[0] samples. Thus,
max_samples should be in the interval (0.0, 1.0].
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.
Prediction computed with out-of-bag estimate on the training set.
This attribute exists only when oob_score is True.
Type:
ndarray of shape (n_samples,) or (n_samples, n_outputs)
See also
sklearn.tree.DecisionTreeRegressor
A decision tree regressor.
sklearn.ensemble.ExtraTreesRegressor
Ensemble of extremely randomized tree regressors.
Notes
The default values for the parameters controlling the size of the trees
(e.g. max_depth, min_samples_leaf, etc.) lead to fully grown and
unpruned trees which can potentially be very large on some data sets. To
reduce memory consumption, the complexity and size of the trees should be
controlled by setting those parameter values.
The features are always randomly permuted at each split. Therefore,
the best found split may vary, even with the same training data,
max_features=n_features and bootstrap=False, if the improvement
of the criterion is identical for several splits enumerated during the
search of the best split. To obtain a deterministic behaviour during
fitting, random_state has to be fixed.
The default value max_features="auto" uses n_features
rather than n_features/3. The latter was originally suggested in
[1], whereas the former was more recently justified empirically in [2].