HistGradientBoostingRegressor
- class sklearn.ensemble.HistGradientBoostingRegressor(loss='squared_error', *, quantile=None, learning_rate=0.1, max_iter=100, max_leaf_nodes=31, max_depth, , , , , , , , , , , , , , ,
Histogram-based Gradient Boosting Regression Tree.
This estimator is much faster than
GradientBoostingRegressor
for big datasets (n_samples >= 10 000).
This estimator has native support for missing values (NaNs). During training, the tree grower learns at each split point whether samples with missing values should go to the left or right child, based on the potential gain. When predicting, samples with missing values are assigned to the left or right child consequently. If no missing values were encountered for a given feature during training, then samples with missing values are mapped to whichever child has the most samples. See Features in Histogram Gradient Boosting Trees for a usecase example of this feature.
This implementation is inspired by LightGBM.
Read more in the User Guide.
The loss function to use in the boosting process. Note that the
“squared error”, “gamma” and “poisson” losses actually implement
“half least squares loss”, “half gamma deviance” and “half poisson
deviance” to simplify the computation of the gradient. Furthermore,
“gamma” and “poisson” losses internally use a log-link, “gamma”
requires y > 0 and “poisson” requires y >= 0.
“quantile” uses the pinball loss.
Indicates whether early stopping is used during training.
n_iter_ : intNumber of iterations of the boosting process.
The number of tree that are built at each iteration. For regressors, this is always 1.
The scores at each iteration on the training data. The first entry
is the score of the ensemble before the first iteration. Scores are
computed according to the scoring parameter. If scoring is
not ‘loss’, scores are computed on a subset of at most 10 000
samples. Empty if no early stopping.
>>> from sklearn.ensemble import HistGradientBoostingRegressor
>>> from sklearn.datasets import load_diabetes
>>> X, y = load_diabetes(return_X_y=True)
>>> est = HistGradientBoostingRegressor().fit(X, y)
Fit the gradient boosting model.
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
A MetadataRequest encapsulating
routing information.
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 values for X.
The input samples.
The predicted values.
Return coefficient of determination on test data.
The coefficient of determination, , is defined as , where is the residual sum of squares and is the total sum of squares . 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 , disregarding the input features, would get a score of 0.0.
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.
Configure whether metadata should be requested to be passed to the method.
Predict regression target for each iteration.
This method allows monitoring (i.e. determine error on testing set) after each stage.
The input samples.
Comparing Random Forests and Histogram Gradient Boosting models
Prediction Intervals for Gradient Boosting Regression
Partial Dependence and Individual Conditional Expectation Plots
Changed in version 1.3: Added option ‘gamma’.
If loss is “quantile”, this parameter specifies which quantile to be estimated and must be between 0 and 1.
The learning rate, also known as shrinkage. This is used as a
multiplicative factor for the leaves values. Use 1 for no
shrinkage.
The maximum number of iterations of the boosting process, i.e. the maximum number of trees.
The maximum number of leaves for each tree. Must be strictly greater than 1. If None, there is no maximum limit.
The maximum depth of each tree. The depth of a tree is the number of edges to go from the root to the deepest leaf. Depth isn’t constrained by default.
The minimum number of samples per leaf. For small datasets with less than a few hundred samples, it is recommended to lower this value since only very shallow trees would be built.
The L2 regularization parameter penalizing leaves with small hessians.
Use 0 for no regularization (default).
Proportion of randomly chosen features in each and every node split.
This is a form of regularization, smaller values make the trees weaker
learners and might prevent overfitting.
If interaction constraints from interaction_cst are present, only allowed
features are taken into account for the subsampling.
The maximum number of bins to use for non-missing values. Before
training, each feature of the input array X is binned into
integer-valued bins, which allows for a much faster training stage.
Features with a small number of unique values may use less than
max_bins bins. In addition to the max_bins bins, one more bin
is always reserved for missing values. Must be no larger than 255.
Indicates the categorical features.
None : no feature will be considered categorical.
boolean array-like : boolean mask indicating categorical features.
integer array-like : integer indices indicating categorical features.
str array-like: names of categorical features (assuming the training data has feature names).
"from_dtype": dataframe columns with dtype “Categorical” and “Enum” are
considered to be categorical features. The input must be a dataframe that
is supported by narwhals (or supports it): narwhals.from_native must
work. This is the case, for instance, for pandas and polars DataFrames.
For each categorical feature, there must be at most max_bins unique
categories. Negative values for categorical features encoded as numeric
dtypes are treated as missing values. All categorical values are
converted to floating point numbers. This means that categorical values
of 1.0 and 1 are treated as the same category.
Read more in the User Guide and Categorical Feature Support in Gradient Boosting.
Monotonic constraint to enforce on each feature are specified using the following integer values:
1: monotonic increase
0: no constraint
-1: monotonic decrease
If a dict with str keys, map feature to monotonic constraints by name. If an array, the features are mapped to constraints by position. See Using feature names to specify monotonic constraints for a usage example.
Read more in the User Guide.
Specify interaction constraints, the sets of features which can interact with each other in child node splits.
Each item specifies the set of feature indices that are allowed to interact with each other. If there are more features than specified in these constraints, they are treated as if they were specified as an additional set.
The strings “pairwise” and “no_interactions” are shorthands for allowing only pairwise or no interactions, respectively.
For instance, with 5 features in total, interaction_cst=[{0, 1}]
is equivalent to interaction_cst=[{0, 1}, {2, 3, 4}],
and specifies that each branch of a tree will either only split
on features 0 and 1 or only split on features 2, 3 and 4.
See this example on how to use interaction_cst.
When set to True, reuse the solution of the previous call to fit
and add more estimators to the ensemble. For results to be valid, the
estimator should be re-trained on the same data only.
See the Glossary.
If ‘auto’, early stopping is enabled if the sample size is larger than
10000 or if X_val and y_val are passed to fit. If True, early stopping
is enabled, otherwise early stopping is disabled.
Scoring method to use for early stopping. Only used if early_stopping
is enabled. Options:
str: see String name scorers for options.
callable: a scorer callable object (e.g., function) with signature
scorer(estimator, X, y). See Callable scorers for details.
None: the coefficient of determination
() is used.
‘loss’: early stopping is checked w.r.t the loss value.
Proportion (or absolute size) of training data to set aside as
validation data for early stopping. If None, early stopping is done on
the training data.
The value is ignored if either early stopping is not performed, e.g.
early_stopping=False, or if X_val and y_val are passed to fit.
Used to determine when to “early stop”. The fitting process is
stopped when none of the last n_iter_no_change scores are better
than the n_iter_no_change - 1 -th-to-last one, up to some
tolerance. Only used if early stopping is performed.
The absolute tolerance to use when comparing scores during early stopping. The higher the tolerance, the more likely we are to early stop: higher tolerance means that it will be harder for subsequent iterations to be considered an improvement upon the reference score.
The verbosity level. If not zero, print some information about the
fitting process. 1 prints only summary info, 2 prints info per
iteration.
Pseudo-random number generator to control the subsampling in the binning process, and the train/validation data split if early stopping is enabled. Pass an int for reproducible output across multiple function calls. See Glossary.
The scores at each iteration on the held-out validation data. The
first entry is the score of the ensemble before the first iteration.
Scores are computed according to the scoring parameter. Empty if
no early stopping or if validation_fraction is None.
Boolean mask for the categorical features. None if there are no
categorical features.
Number of features seen during fit.
n_features_in_,)Names of features seen during fit. Defined only when X
has feature names that are all strings.
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.
The input samples.
Target values.
Weights of training data.
Additional sample of features for validation used in early stopping.
In a Pipeline, X_val can be transformed the same way as X with
Pipeline(..., transform_input=["X_val"]).
Additional sample of target values for validation used in early stopping.
Additional weights for validation used in early stopping.
Fitted estimator.
((y_true - y_pred)** 2).sum()((y_true - y_true.mean()) ** 2).sum()yTest 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.
of self.predict(X) w.r.t. y.
The 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).
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Metadata routing for X_val parameter in fit.
Metadata routing for sample_weight parameter in fit.
Metadata routing for parameter in .
Estimator instance.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to score if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to score.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Metadata routing for sample_weight parameter in score.
The updated object.
The predicted values of the input samples, for each iteration.
fitMetadata routing for y_val parameter in fit.
The updated object.