sklearn.ensemble
.HistGradientBoostingClassifier¶
-
class
sklearn.ensemble.
HistGradientBoostingClassifier
(loss='auto', learning_rate=0.1, max_iter=100, max_leaf_nodes=31, max_depth=None, min_samples_leaf=20, l2_regularization=0.0, max_bins=255, warm_start=False, scoring=None, validation_fraction=0.1, n_iter_no_change=None, tol=1e-07, verbose=0, random_state=None)[source]¶ Histogram-based Gradient Boosting Classification Tree.
This estimator is much faster than
GradientBoostingClassifier
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.
This implementation is inspired by LightGBM.
Note
This estimator is still experimental for now: the predictions and the API might change without any deprecation cycle. To use it, you need to explicitly import
enable_hist_gradient_boosting
:>>> # explicitly require this experimental feature >>> from sklearn.experimental import enable_hist_gradient_boosting # noqa >>> # now you can import normally from ensemble >>> from sklearn.ensemble import HistGradientBoostingClassifier
Read more in the User Guide.
New in version 0.21.
- Parameters
- loss{‘auto’, ‘binary_crossentropy’, ‘categorical_crossentropy’}, optional (default=’auto’)
The loss function to use in the boosting process. ‘binary_crossentropy’ (also known as logistic loss) is used for binary classification and generalizes to ‘categorical_crossentropy’ for multiclass classification. ‘auto’ will automatically choose either loss depending on the nature of the problem.
- learning_ratefloat, optional (default=0.1)
The learning rate, also known as shrinkage. This is used as a multiplicative factor for the leaves values. Use
1
for no shrinkage.- max_iterint, optional (default=100)
The maximum number of iterations of the boosting process, i.e. the maximum number of trees for binary classification. For multiclass classification,
n_classes
trees per iteration are built.- max_leaf_nodesint or None, optional (default=31)
The maximum number of leaves for each tree. Must be strictly greater than 1. If None, there is no maximum limit.
- max_depthint or None, optional (default=None)
The maximum depth of each tree. The depth of a tree is the number of nodes to go from the root to the deepest leaf. Must be strictly greater than 1. Depth isn’t constrained by default.
- min_samples_leafint, optional (default=20)
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.
- l2_regularizationfloat, optional (default=0)
The L2 regularization parameter. Use 0 for no regularization.
- max_binsint, optional (default=255)
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 thanmax_bins
bins. In addition to themax_bins
bins, one more bin is always reserved for missing values. Must be no larger than 255.- warm_startbool, optional (default=False)
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.- scoringstr or callable or None, optional (default=None)
Scoring parameter to use for early stopping. It can be a single string (see The scoring parameter: defining model evaluation rules) or a callable (see Defining your scoring strategy from metric functions). If None, the estimator’s default scorer is used. If
scoring='loss'
, early stopping is checked w.r.t the loss value. Only used ifn_iter_no_change
is not None.- validation_fractionint or float or None, optional (default=0.1)
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.
- n_iter_no_changeint or None, optional (default=None)
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 then_iter_no_change - 1
-th-to-last one, up to some tolerance. If None or 0, no early-stopping is done.- tolfloat or None, optional (default=1e-7)
The absolute tolerance to use when comparing scores. 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.
- verbose: int, optional (default=0)
The verbosity level. If not zero, print some information about the fitting process.
- random_stateint, np.random.RandomStateInstance or None, optional (default=None)
Pseudo-random number generator to control the subsampling in the binning process, and the train/validation data split if early stopping is enabled. See random_state.
- Attributes
- n_iter_int
The number of estimators as selected by early stopping (if n_iter_no_change is not None). Otherwise it corresponds to max_iter.
- n_trees_per_iteration_int
The number of tree that are built at each iteration. This is equal to 1 for binary classification, and to
n_classes
for multiclass classification.- train_score_ndarray, shape (n_iter_+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. Ifscoring
is not ‘loss’, scores are computed on a subset of at most 10 000 samples. Empty if no early stopping.- validation_score_ndarray, shape (n_iter_+1,)
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 ifvalidation_fraction
is None.
Examples
>>> # To use this experimental feature, we need to explicitly ask for it: >>> from sklearn.experimental import enable_hist_gradient_boosting # noqa >>> from sklearn.ensemble import HistGradientBoostingClassifier >>> from sklearn.datasets import load_iris >>> X, y = load_iris(return_X_y=True) >>> clf = HistGradientBoostingClassifier().fit(X, y) >>> clf.score(X, y) 1.0
Methods
decision_function
(self, X)Compute the decision function of X.
fit
(self, X, y)Fit the gradient boosting model.
get_params
(self[, deep])Get parameters for this estimator.
predict
(self, X)Predict classes for X.
predict_proba
(self, X)Predict class probabilities for X.
score
(self, X, y[, sample_weight])Return the mean accuracy on the given test data and labels.
set_params
(self, \*\*params)Set the parameters of this estimator.
-
__init__
(self, loss='auto', learning_rate=0.1, max_iter=100, max_leaf_nodes=31, max_depth=None, min_samples_leaf=20, l2_regularization=0.0, max_bins=255, warm_start=False, scoring=None, validation_fraction=0.1, n_iter_no_change=None, tol=1e-07, verbose=0, random_state=None)[source]¶ Initialize self. See help(type(self)) for accurate signature.
-
decision_function
(self, X)[source]¶ Compute the decision function of X.
- Parameters
- Xarray-like, shape (n_samples, n_features)
The input samples.
- Returns
- decisionndarray, shape (n_samples,) or (n_samples, n_trees_per_iteration)
The raw predicted values (i.e. the sum of the trees leaves) for each sample. n_trees_per_iteration is equal to the number of classes in multiclass classification.
-
fit
(self, X, y)[source]¶ Fit the gradient boosting model.
- Parameters
- Xarray-like of shape (n_samples, n_features)
The input samples.
- yarray-like of shape (n_samples,)
Target values.
- Returns
- selfobject
-
get_params
(self, deep=True)[source]¶ Get parameters for this estimator.
- Parameters
- deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators.
- Returns
- paramsmapping of string to any
Parameter names mapped to their values.
-
predict
(self, X)[source]¶ Predict classes for X.
- Parameters
- Xarray-like, shape (n_samples, n_features)
The input samples.
- Returns
- yndarray, shape (n_samples,)
The predicted classes.
-
predict_proba
(self, X)[source]¶ Predict class probabilities for X.
- Parameters
- Xarray-like, shape (n_samples, n_features)
The input samples.
- Returns
- pndarray, shape (n_samples, n_classes)
The class probabilities of the input samples.
-
score
(self, X, y, sample_weight=None)[source]¶ Return the mean accuracy on the given test data and labels.
In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.
- Parameters
- Xarray-like of shape (n_samples, n_features)
Test samples.
- yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True labels for X.
- sample_weightarray-like of shape (n_samples,), default=None
Sample weights.
- Returns
- scorefloat
Mean accuracy of self.predict(X) wrt. y.
-
set_params
(self, **params)[source]¶ Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as pipelines). The latter have parameters of the form
<component>__<parameter>
so that it’s possible to update each component of a nested object.- Parameters
- **paramsdict
Estimator parameters.
- Returns
- selfobject
Estimator instance.