This page gives the Python API reference of xgboost, please also refer to Python Package Introduction for more information about the Python package.
Global Configuration
xgboost.config_context(**new_config)
Context manager for global XGBoost configuration.
Global configuration consists of a collection of parameters that can be applied in the
global scope. See Global Configuration for the full list of parameters supported in
the global configuration.
New
Added in version 1.4.0.
Parameters:
new_config (Dict[str, Any]) – Keyword arguments representing the parameters and their values
importxgboostasxgb# Show all messages, including ones pertaining to debuggingxgb.set_config(verbosity=2)# Get current value of global configuration# This is a dict containing all parameters in the global configuration,# including 'verbosity'config=xgb.get_config()assertconfig['verbosity']==2# Example of using the context manager xgb.config_context().# The context manager will restore the previous value of the global# configuration upon exiting.withxgb.config_context(verbosity=0):# Suppress warning caused by model generated with XGBoost version < 1.0.0bst=xgb.Booster(model_file='./old_model.bin')assertxgb.get_config()['verbosity']==2# old value restored
Global configuration consists of a collection of parameters that can be applied in the
global scope. See Global Configuration for the full list of parameters supported in
the global configuration.
Parameters:
new_config (Dict[str, Any]) – Keyword arguments representing the parameters and their values
Return type:
None
Example
importxgboostasxgb# Show all messages, including ones pertaining to debuggingxgb.set_config(verbosity=2)# Get current value of global configuration# This is a dict containing all parameters in the global configuration,# including 'verbosity'config=xgb.get_config()assertconfig['verbosity']==2# Example of using the context manager xgb.config_context().# The context manager will restore the previous value of the global
Global configuration consists of a collection of parameters that can be applied in the
global scope. See Global Configuration for the full list of parameters supported in
the global configuration.
Returns:
args – The list of global parameters and their values
importxgboostasxgb# Show all messages, including ones pertaining to debuggingxgb.set_config(verbosity=2)# Get current value of global configuration# This is a dict containing all parameters in the global configuration,# including 'verbosity'config=xgb.get_config()assertconfig['verbosity']==2# Example of using the context manager xgb.config_context().# The context manager will restore the previous value of the global# configuration upon exiting.with
Build information of XGBoost. The returned value format is not stable. Also,
please note that build time dependency is not the same as runtime dependency. For
instance, it’s possible to build XGBoost with older CUDA version but run it with the
lastest one.
DMatrix is an internal data structure that is used by XGBoost, which is optimized
for both memory efficiency and training speed. You can construct DMatrix from
multiple different sources of data.
Data source of DMatrix. See Markers for a list of supported input
types.
Note that, if passing an iterator, it will cache data on disk, and note
that fields like label will be concatenated in-memory from multiple
calls to the iterator.
The interface for user defined data iterator. The iterator facilitates
distributed training, QuantileDMatrix, and external memory support using
or . Most of time, users don’t
need to interact with this class directly.
An internal storage class for categories returned by the DMatrix and the
Booster. This class is designed to be opaque. It is intended to be used exclusively
by XGBoost as an intermediate storage for re-coding categorical data.
The categories are saved along with the booster object. As a result, users don’t
need to preserve this class for re-coding. Use the booster model IO instead if you
want to preserve the categories in a stable format.
num_boost_round (int) – Number of boosting iterations.
evals (Sequence[) – List of validation sets for which metrics will evaluated during training.
Validation metrics will help us track the performance of the model.
The best iteration obtained by early stopping. This attribute is 0-based,
for instance if the best iteration is the first round, then best_iteration is 0.
If eval_set is passed to the fit() function, you can call
evals_result() to get evaluation results for all passed eval_sets. When
eval_metric is also passed to the fit() function, the
evals_result will contain the eval_metrics passed to the fit()
function.
Feature importances property, return depends on importance_type
parameter. When model trained with multi-class/multi-label/multi-target dataset,
the feature importance is “averaged” over all targets. The “average” is defined
based on the importance type. For instance, if the importance type is
“total_gain”, then the score is sum of loss change for each split from all
trees.
Returns:
feature_importances_ (array of shape [n_features] except for multi-class)
linear model, which returns an array with shape (n_features, n_classes)
For tree-based model, the returned value is the base_score.
Returns:
intercept_
Return type:
array of shape (1,) or [n_classes]
load_model(fname)
Load the model from a file or a bytearray.
The model is saved in an XGBoost internal format which is universal among the
various XGBoost interfaces. Auxiliary attributes of the Python Booster object
(such as feature_names) are only saved when using JSON or UBJSON (default)
format. Also, parameters that are not part of the model (like metrics,
max_depth, etc) are not saved, see Model IO
for more info.
Predict with X. If the model is trained with early stopping, then
best_iteration is used automatically. The estimator uses
inplace_predict by default and falls back to using if
devices between the data and the estimator don’t match.
save_model(fname)
Save the model to a file.
The model is saved in an XGBoost internal format which is universal among the
various XGBoost interfaces. Auxiliary attributes of the Python Booster object
(such as feature_names) are only saved when using JSON or UBJSON (default)
format. Also, parameters that are not part of the model (like metrics,
max_depth, etc) are not saved, see Model IO
for more info.
The coefficient of determination, R2, is defined as
(1−vu), 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. Modification of the sklearn method to
allow unknown kwargs. This allows using the full range of xgboost
parameters that are not defined as member variables in sklearn grid
search.
Configure whether metadata should be requested to be passed to the predict 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 ).
Please check the on how the routing
mechanism works.
set_score_request(*, sample_weight='$UNCHANGED$')
Configure whether metadata should be requested to be passed to the score 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.
learning_rates (Callable[[) – If it’s a callable object, then it should accept an integer parameter
and returns the corresponding learning rate. Otherwise it
should be a sequence like list or tuple with the same size of boosting
rounds.
Checkpointing operation. Users are encouraged to create their own callbacks for
checkpoint as XGBoost doesn’t handle distributed file systems. When checkpointing on
distributed systems, be sure to know the rank of the worker to avoid multiple
workers checkpointing to the same place.
SparkXGBClassifier is a PySpark ML estimator. It implements the XGBoost
classification algorithm based on XGBoost python library, and it can be used in
PySpark Pipeline and PySpark ML meta algorithms like
- CrossValidator/
- TrainValidationSplit/
- OneVsRest
SparkXGBClassifier automatically supports most of the parameters in
xgboost.XGBClassifier constructor and most of the parameters used in
and
method.
User configuration for the communicator context. This is used for easier
integration with distributed frameworks. Users of the collective module can pass the
parameters directly into tracker and the communicator.
See dmlc_timeout in init(). This is only used for communicators, not
the tracker. They are different parameters since the timeout for tracker limits
only the time for starting and finalizing the communication group, whereas the
timeout for communicators limits the time used for collective operations, like
allreduce().
Keyword arguments representing the parameters and their values.
Accepted parameters:
dmlc_communicator: The type of the communicator.
* rabit: Use Rabit. This is the default if the type is unspecified.
* federated: Use the gRPC interface for Federated Learning.
Set types for features. If data is a DataFrame type and passing
enable_categorical=True, the types will be deduced automatically from the
column types.
Otherwise, one can pass a list-like input with the same length as number of
columns in data, with the following possible values:
”c”, which represents categorical columns.
”q”, which represents numeric columns.
”int”, which represents integer columns.
”i”, which represents boolean columns.
Note that, while categorical types are treated differently from the rest for
model fitting purposes, the other types do not influence the generated
model, but have effects in other functionalities such as feature
importances.
For categorical features, the input is assumed to be preprocessed and
encoded by the users. The encoding can be done via
sklearn.preprocessing.OrdinalEncoder or pandas dataframe
.cat.codes method. This is useful when users want to specify categorical
features without having to construct a dataframe as input.
Alternatively, user can pass a Categories object
returned from previous training as a reference for re-coding. One can obtain
the reference with the get_categories() from the previous training
DMatrix or the Booster. This feature is experimental.
nthread (int | None) – Number of threads to use for loading data when parallelization is
applicable. If -1, uses maximum threads available on the system.
group (Any | None) – Group size for all ranking group.
qid (Any | None) – Query ID for data samples, used for ranking.
label_lower_bound (Any | None) – Lower bound for survival training.
label_upper_bound (Any | None) – Upper bound for survival training.
feature_weights (Any | None) – Set feature weights for column sampling.
Experimental support of specializing for categorical features. See
Categorical Data for more info.
If passing True and data is a data frame (from supported libraries such
as Pandas, Modin, polars, and cuDF), The DMatrix recognizes categorical
columns and automatically set the feature_types parameter. If data is
not a data frame, this argument is ignored.
If passing False and data is a data frame with categorical columns, it
will result in an error.
See notes in the DataIter for consistency requirement when the
input is an iterator.
XGBoost can remember the encoding of categories when the input is a
dataframe.
Get the predictors from DMatrix as a CSR matrix. This getter is mostly for
testing purposes. If this is a quantized DMatrix then quantized values are
returned instead of input values.
Save DMatrix to an XGBoost buffer. Saved binary can be later loaded
by providing the path to xgboost.DMatrix() as input.
Parameters:
fname (string or os.PathLike) – Name of the output buffer file.
silent (bool (optional; default: True)) – If set, the output is suppressed.
Return type:
None
set_base_margin(margin)
Set base margin of booster to start from.
This can be used to specify a prediction value of existing model to be
base_margin However, remember margin is needed, instead of transformed
prediction e.g. for logistic regression: need to put in value before
logistic transformation see also example/demo.py
Parameters:
margin (array like) – Prediction margin of each datapoint
A DMatrix variant that generates quantilized data directly from input for the
hist tree method. This DMatrix is primarily designed to save memory in training
by avoiding intermediate storage. Set max_bin to control the number of bins
during quantisation, which should be consistent with the training parameter
max_bin. When QuantileDMatrix is used for validation/test dataset, ref
should be another QuantileDMatrix or DMatrix, but not recommended as it
defeats the purpose of saving memory) constructed from training dataset. See
xgboost.DMatrix for documents on meta info.
max_bin (int | None) – The number of histogram bin, should be consistent with the training parameter
max_bin.
ref (DMatrix | None) – The training dataset that provides quantile information, needed when creating
validation/test dataset with QuantileDMatrix. Supplying the training DMatrix
as a reference means that the same quantisation applied to the training data is
applied to the validation/test data
For GPU-based inputs from an iterator, XGBoost handles incoming batches with
multiple growing sub-streams. This parameter sets the maximum number of batches
before XGBoost can cut a sub-stream and create a new one. This can help bound
the memory usage. By default, XGBoost grows a sub-stream exponentially until
batches are exhausted. This option is only used for the training dataset and the
default is None (unbounded). Lastly, if the is a single batch instead of
an iterator, this parameter has no effect.
export_to_arrow (bool) – The returned container will contain a list of arrays for the
categories. See the for more info.
get_data()
Get the predictors from DMatrix as a CSR matrix. This getter is mostly for
testing purposes. If this is a quantized DMatrix then quantized values are
returned instead of input values.
Internal method for retrieving a reference to the training DMatrix.
save_binary(fname, silent=True)
Save DMatrix to an XGBoost buffer. Saved binary can be later loaded
by providing the path to xgboost.DMatrix() as input.
Parameters:
fname (string or os.PathLike) – Name of the output buffer file.
silent (bool (optional; default: True) – If set, the output is suppressed.
set_base_margin(margin)
Set base margin of booster to start from.
This can be used to specify a prediction value of existing model to be
base_margin However, remember margin is needed, instead of transformed
prediction e.g. for logistic regression: need to put in value before
logistic transformation see also example/demo.py
Parameters:
margin (array like) – Prediction margin of each datapoint
Used by the GPU implementation. For GPU-based inputs, XGBoost can split the
cache into host and device caches to reduce the data transfer overhead. This
parameter specifies the size of host cache compared to the size of the
entire cache: host/(host+device).
Get the predictors from DMatrix as a CSR matrix. This getter is mostly for
testing purposes. If this is a quantized DMatrix then quantized values are
returned instead of input values.
Internal method for retrieving a reference to the training DMatrix.
save_binary(fname, silent=True)
Save DMatrix to an XGBoost buffer. Saved binary can be later loaded
by providing the path to xgboost.DMatrix() as input.
Parameters:
fname (string or os.PathLike) – Name of the output buffer file.
silent (bool (optional; default: True)) – If set, the output is suppressed.
Return type:
None
set_base_margin(margin)
Set base margin of booster to start from.
This can be used to specify a prediction value of existing model to be
base_margin However, remember margin is needed, instead of transformed
prediction e.g. for logistic regression: need to put in value before
logistic transformation see also example/demo.py
Parameters:
margin (array like) – Prediction margin of each datapoint
Dump model into a text or JSON file. Unlike save_model(), the
output format is primarily used for visualization or interpretation,
hence it’s more human readable but cannot be loaded back to XGBoost.
Returns the model dump as a list of strings. Unlike save_model(),
the output format is primarily used for visualization or interpretation, hence
it’s more human readable but cannot be loaded back to XGBoost.
Parameters:
fmap (str | PathLike) – Name of the file containing feature map names.
with_stats (bool) – Controls whether the split statistics should be included.
dump_format (str) – Format of model dump. Can be ‘text’, ‘json’ or ‘dot’.
Run prediction in-place when possible, Unlike predict() method,
inplace prediction does not cache the prediction result.
Calling only inplace_predict in multiple threads is safe and lock
free. But the safety does not hold when used in conjunction with other
methods. E.g. you can’t train the booster in one thread and perform
prediction in the other.
The model is saved in an XGBoost internal format which is universal among the
various XGBoost interfaces. Auxiliary attributes of the Python Booster object
(such as feature_names) are only saved when using JSON or UBJSON (default)
format. Also, parameters that are not part of the model (like metrics,
max_depth, etc) are not saved, see Model IO
for more info.
Predict with data. The full model will be used unless iteration_range is
specified, meaning user have to either slice the model or use the
best_iteration attribute to get prediction from best model returned from
early stopping.
output_margin (bool) – Whether to output the raw untransformed margin value.
pred_leaf () – When this option is on, the output will be a matrix of (nsample,
ntrees) with each record indicating the predicted leaf index of
each sample in each tree. Note that the leaf index of a tree is
unique per tree, so you may find leaf 1 in both tree 1 and tree 0.
reset()
Reset the booster object to release data caches used for training.
The model is saved in an XGBoost internal format which is universal among the
various XGBoost interfaces. Auxiliary attributes of the Python Booster object
(such as feature_names) are only saved when using JSON or UBJSON (default)
format. Also, parameters that are not part of the model (like metrics,
max_depth, etc) are not saved, see Model IO
for more info.
Save the model to a in memory buffer representation instead of file.
The model is saved in an XGBoost internal format which is universal among the
various XGBoost interfaces. Auxiliary attributes of the Python Booster object
(such as feature_names) are only saved when using JSON or UBJSON (default)
format. Also, parameters that are not part of the model (like metrics,
max_depth, etc) are not saved, see Model IO
for more info.
Parameters:
raw_format (str) – Format of output buffer. Can be json or ubj.
Return type:
An in memory buffer representation of the model
set_attr(**kwargs)
Set the attribute of the Booster.
Parameters:
**kwargs (Any | None) – The attributes to set. Setting a value to None deletes an attribute.
Return type:
None
set_param(params, value=None)
Set parameters into the Booster.
Parameters:
params (Dict | Iterable[Tuple[str, Any]] | str) – list of key,value pairs, dict of key to value or simply str key
value (str | None) – value of the specified parameter, when params is str key
Return type:
None
trees_to_dataframe(fmap='')
Parse a boosted tree model text dump into a pandas DataFrame structure.
This feature is only defined when the decision tree model is chosen as base
learner (booster in {gbtree, dart}). It is not defined for other base learner
types, such as linear learners (booster=gblinear).
Parameters:
fmap (str | PathLike) – The name of feature map file.
Return type:
PdDataFrame
update(dtrain, iteration, fobj=None)
Update for one iteration, with objective function calculated
internally.
Prefix to the cache files, only used in external memory.
Note that using this class for external memory will cache data
on disk under the path passed here.
release_data (bool) – Whether the iterator should release the data during iteration. Set it to True if
the data transformation (converting data to np.float32 type) is memory
intensive. Otherwise, if the transformation is computation intensive then we can
keep the cache.
Whether the data should be cached on the host memory instead of the file system
when using GPU with external memory. When set to true (the default), the
“external memory” is the CPU (host) memory. See
Using XGBoost External Memory Version for more info.
The minimum number of bytes of each cached pages. Only used for on-host cache
with GPU-based ExtMemQuantileDMatrix. When using GPU-based external
memory with the data cached in the host memory, XGBoost can concatenate the
pages internally to increase the batch size for the GPU. The default page size
is about 1/16 of the total device memory. Users can manually set the value based
on the actual hardware and datasets. Set this to 0 to disable page
concatenation.
get_callbacks(enable_categorical)
Get callback functions for iterating in C. This is an internal function.
input_data (Callable) – A function with same data fields like data, label with
xgboost.DMatrix.
Return type:
False if there’s no more batch, otherwise True.
propertyproxy:_ProxyDMatrix
Handle of DMatrix proxy.
reraise()
Reraise the exception thrown during iteration.
Return type:
None
abstractreset()
Reset the data iterator. Prototype for user defined function.
Return type:
None
Xy=xgboost.QuantileDMatrix(X,y,enable_categorical=True)booster=xgboost.train({},Xy)categories=booster.get_categories()# Get categories# Use categories as a reference for re-codingXy_new=xgboost.QuantileDMatrix(X_new,y_new,feature_types=categories,enable_categorical=True,ref=Xy)# Categories will be part of the `model.json`.booster.save_model("model.json")
Activates early stopping. Validation metric needs to improve at least once in
every early_stopping_rounds round(s) to continue training.
Requires at least one item in evals.
The method returns the model from the last iteration (not the best one). Use
custom callback EarlyStopping or modelslicing if the best model is desired. If there’s
more than one item in evals, the last entry will be used for early stopping.
If there’s more than one metric in the eval_metric parameter given in
params, the last metric will be used for early stopping.
If early stopping occurs, the model will have two additional fields:
bst.best_score, bst.best_iteration.
If verbose_eval is True then the evaluation metric on the validation set is
printed at each boosting stage.
If verbose_eval is an integer then the evaluation metric on the validation
set is printed at every given verbose_eval boosting stage. The last boosting
stage / the boosting stage found by using early_stopping_rounds is also
printed.
Example: with verbose_eval=4 and at least one item in evals, an
evaluation metric is printed every 4 boosting stages, instead of every boosting
stage.
xgb_model (str | PathLike | Booster | bytearray | None) – Xgb model to be loaded before training (allows training continuation).
List of callback functions that are applied at end of each iteration.
It is possible to use predefined callbacks by using
Callback API.
forparamsinparameters_grid:# be sure to (re)initialize the callbacks before each runcallbacks=[xgb.callback.LearningRateScheduler(custom_rates)]xgboost.train(params,Xy,callbacks=callbacks)
Custom metric function. See Custom Metric
for details. The metric receives transformed prediction (after applying the
reverse link function) when using a builtin objective, and raw output when using
a custom objective.
folds (a KFold or StratifiedKFold instance or list of fold indices) – Sklearn KFolds or StratifiedKFolds object.
Alternatively may explicitly pass sample indices for each fold.
For n folds, folds should be a length n list of tuples.
Each tuple is (in,out) where in is a list of indices to be used
as the training samples for the n th fold and out is a list of
indices to be used as the testing samples for the n th fold.
metrics (string or list of strings) – Evaluation metrics to be watched in CV.
maximize (bool) – Whether to maximize the evaluataion metric (score or error).
early_stopping_rounds (int) – Activates early stopping. Cross-Validation metric (average of validation
metric computed over CV folds) needs to improve at least once in
every early_stopping_rounds round(s) to continue training.
The last entry in the evaluation history will represent the best iteration.
If there’s more than one metric in the eval_metric parameter given in
params, the last metric will be used for early stopping.
fpreproc (function) – Preprocessing function that takes (dtrain, dtest, param) and returns
transformed versions of those.
as_pandas (bool, default True) – Return pd.DataFrame when pandas is installed.
If False or pandas is not installed, return np.ndarray
verbose_eval (bool, int, or None, default None) – Whether to display the progress. If None, progress will be displayed
when np.ndarray is returned. If True, progress will be displayed at
boosting stage. If an integer is given, progress will be displayed
at every given verbose_eval boosting stage.
show_stdv (bool, default True) – Whether to display the standard deviation in progress.
Results are not affected, and always contains std.
seed (int) – Seed used to generate the folds (passed to numpy.random.seed).
booster (Optional[str]) – Specify which booster to use: gbtree, gblinear or dart.
tree_method (Optional[str]) – Specify which tree method to use. Default to auto. If this parameter is set to
default, XGBoost will choose the most conservative option available. It’s
recommended to study this option from the parameters document tree method
n_jobs (Optional[int]) – Number of parallel threads used to run xgboost. When used with other
Scikit-Learn algorithms like grid search, you may choose which algorithm to
parallelize and balance the threads. Creating thread contention will
significantly slow down both algorithms.
gamma (Optional[float]) – (min_split_loss) Minimum loss reduction required to make a further partition on
a leaf node of the tree.
min_child_weight (Optional[float]) – Minimum sum of instance weight(hessian) needed in a child.
max_delta_step (Optional[float]) – Maximum delta step we allow each tree’s weight estimation to be.
subsample (Optional[float]) – Subsample ratio of the training instance.
missing (float) – Value in the data which needs to be present as a missing value. Default to
numpy.nan.
num_parallel_tree (Optional[int]) – Used for boosting random forest.
monotone_constraints (Union[Dict[str, int], str, NoneType]) – Constraint of variable monotonicity. See tutorial
for more information.
interaction_constraints (Union[str, List[Tuple[str]], NoneType]) – Constraints for interaction representing permitted interactions. The
constraints must be specified in the form of a nested list, e.g. [[0,1],[2,3,4]], where each inner list is a group of indices of features that are
allowed to interact with each other. See tutorial for more information
Used for specifying feature types without constructing a dataframe. See
the DMatrix for details.
feature_weights (Optional[ArrayLike]) – Weight for each feature, defines the probability of each feature being selected
when colsample is being used. All values must be greater than 0, otherwise a
ValueError is thrown.
A threshold for deciding whether XGBoost should use one-hot encoding based split
for categorical data. When number of categories is lesser than the threshold
then one-hot encoding is chosen, otherwise the categories will be partitioned
into children nodes. Also, enable_categorical needs to be set to have
categorical feature support. See Categorical Data and Parameters for Categorical Feature for details.
Maximum number of categories considered for each split. Used only by
partition-based splits for preventing over-fitting. Also, enable_categorical
needs to be set to have categorical feature support. See Categorical Data and Parameters for Categorical Feature for details.
The strategy used for training multi-target models, including multi-target
regression and multi-class classification. See Multiple Outputs for
more information.
Metric used for monitoring the training result and early stopping. It can be a
string or list of strings as names of predefined metric in XGBoost (See
XGBoost Parameters), one of the metrics in sklearn.metrics, or any
other user defined metric that looks like sklearn.metrics.
If custom objective is also provided, then custom metric should implement the
corresponding reverse link function.
Unlike the scoring parameter commonly used in scikit-learn, when a callable
object is provided, it’s assumed to be a cost function and by default XGBoost
will minimize the result during early stopping.
For advanced usage on Early stopping like directly choosing to maximize instead
of minimize, see xgboost.callback.EarlyStopping.
Activates early stopping. Validation metric needs to improve at least once in
every early_stopping_rounds round(s) to continue training. Requires at
least one item in eval_set in fit().
If early stopping occurs, the model will have two additional attributes:
best_score and best_iteration. These are used by the
predict() and apply() methods to determine the optimal
number of trees during inference. If users want to access the full model
(including trees built after early stopping), they can specify the
iteration_range in these inference methods. In addition, other utilities
like model plotting can also use the entire model.
If you prefer to discard the trees after best_iteration, consider using the
callback function xgboost.callback.EarlyStopping.
If there’s more than one item in eval_set, the last entry will be used for
early stopping. If there’s more than one metric in eval_metric, the last
metric will be used for early stopping.
List of callback functions that are applied at end of each iteration.
It is possible to use predefined callbacks by using
Callback API.
forparamsinparameters_grid:# be sure to (re)initialize the callbacks before each runcallbacks=[xgb.callback.LearningRateScheduler(custom_rates)]reg=xgboost.XGBRegressor(**params,callbacks=callbacks)reg.fit(X,y)
Keyword arguments for XGBoost Booster object. Full documentation of parameters
can be found here.
Attempting to set a parameter via the constructor args and **kwargs
dict simultaneously will result in a TypeError.
X_leaves – For each datapoint x in X and for each tree, return the index of the
leaf x ends up in. Leaves are numbered within
[0;2**(self.max_depth+1)), possibly with gaps in the numbering.
Note that calling fit() multiple times will cause the model object to be
re-fit from scratch. To resume training from a previous checkpoint, explicitly
pass xgb_model argument.
Input feature matrix. See Markers for a list of supported types.
When the tree_method is set to hist, internally, the
QuantileDMatrix will be used instead of the DMatrix
for conserving memory. However, this has performance implications when the
device of input data is not matched with algorithm. For instance, if the
input is a numpy array on CPU but cuda is used for training, then the
data is first processed on CPU then transferred to GPU.
base_margin (Any | None) – Global bias for each instance. See Intercept for details.
eval_set (Sequence[Tuple[Any, Any]] | None) – A list of (X, y) tuple pairs to use as validation sets, for which
metrics will be computed.
Validation metrics will help us track the performance of the model.
verbose (bool | int | None) – If verbose is True and an evaluation set is used, the evaluation metric
measured on the validation set is printed to stdout at each boosting stage.
If verbose is an integer, the evaluation metric is printed at each
verbose boosting stage. The last boosting stage / the boosting stage found
by using early_stopping_rounds is also printed.
xgb_model (Booster | XGBModel | str | None) – file name of stored XGBoost model or ‘Booster’ instance XGBoost model to be
loaded before training (allows training continuation).
sample_weight_eval_set (Sequence[Any] | None) – A list of the form [L_1, L_2, …, L_n], where each L_i is an array like
object storing instance weights for the i-th validation set.
base_margin_eval_set (Sequence[Any] | None) – A list of the form [M_1, M_2, …, M_n], where each M_i is an array like
object storing base margin for the i-th validation set.
Use feature_weights in __init__() or set_params()
instead.
Return type:
XGBModel
(
"model.ubj"
)
model
.
load_model
(
"model.ubj"
)
# or
buf
=
model
.
save_raw
()
model
.
load_model
(
buf
)
Parameters:
fname (PathLike | bytearray | str) – Input file name or memory buffer(see also save_raw)
Return type:
None
DMatrix
Parameters:
X (Any) – Data to predict with. See Markers for a list of supported types.
output_margin (bool) – Whether to output the raw untransformed margin value.
validate_features (bool) – When this is True, validate that the Booster’s and data’s feature_names are
identical. Otherwise, it is assumed that the feature_names are the same.
base_margin (Any | None) – Global bias for each instance. See Intercept for details.
Specifies which layer of trees are used in prediction. For example, if a
random forest is trained with 100 rounds. Specifying iteration_range=(10,20), then only the forests built during [10, 20) (half open set) rounds
are used in this prediction.
X (array-like of shape (n_samples, n_features)) – Test samples. For some estimators this may be a precomputed
kernel matrix or a list of generic objects instead with shape
(n_samples,n_samples_fitted), where n_samples_fitted
is the number of samples used in the fitting for the estimator.
y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – True values for X.
sample_weight (array-like of shape (n_samples,), default=None) – Sample weights.
The R2 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.
Parameters:
base_margin (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for base_margin parameter in fit.
base_margin_eval_set (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for base_margin_eval_set parameter in .
True: metadata is requested, and passed to predict 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 predict.
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.
Parameters:
base_margin (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for base_margin parameter in predict.
iteration_range (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for iteration_range parameter in predict.
output_margin (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for output_margin parameter in predict.
validate_features (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for validate_features parameter in predict.
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.
Parameters:
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in score.
booster (Optional[str]) – Specify which booster to use: gbtree, gblinear or dart.
tree_method (Optional[str]) – Specify which tree method to use. Default to auto. If this parameter is set to
default, XGBoost will choose the most conservative option available. It’s
recommended to study this option from the parameters document tree method
n_jobs (Optional[int]) – Number of parallel threads used to run xgboost. When used with other
Scikit-Learn algorithms like grid search, you may choose which algorithm to
parallelize and balance the threads. Creating thread contention will
significantly slow down both algorithms.
gamma (Optional[float]) – (min_split_loss) Minimum loss reduction required to make a further partition on
a leaf node of the tree.
min_child_weight (Optional[float]) – Minimum sum of instance weight(hessian) needed in a child.
max_delta_step (Optional[float]) – Maximum delta step we allow each tree’s weight estimation to be.
subsample (Optional[float]) – Subsample ratio of the training instance.
missing (float) – Value in the data which needs to be present as a missing value. Default to
numpy.nan.
num_parallel_tree (Optional[int]) – Used for boosting random forest.
monotone_constraints (Union[Dict[str, int], str, NoneType]) – Constraint of variable monotonicity. See tutorial
for more information.
interaction_constraints (Union[str, List[Tuple[str]], NoneType]) – Constraints for interaction representing permitted interactions. The
constraints must be specified in the form of a nested list, e.g. [[0,1],[2,3,4]], where each inner list is a group of indices of features that are
allowed to interact with each other. See tutorial for more information
Used for specifying feature types without constructing a dataframe. See
the DMatrix for details.
feature_weights (Optional[ArrayLike]) – Weight for each feature, defines the probability of each feature being selected
when colsample is being used. All values must be greater than 0, otherwise a
ValueError is thrown.
A threshold for deciding whether XGBoost should use one-hot encoding based split
for categorical data. When number of categories is lesser than the threshold
then one-hot encoding is chosen, otherwise the categories will be partitioned
into children nodes. Also, enable_categorical needs to be set to have
categorical feature support. See Categorical Data and Parameters for Categorical Feature for details.
Maximum number of categories considered for each split. Used only by
partition-based splits for preventing over-fitting. Also, enable_categorical
needs to be set to have categorical feature support. See Categorical Data and Parameters for Categorical Feature for details.
The strategy used for training multi-target models, including multi-target
regression and multi-class classification. See Multiple Outputs for
more information.
Metric used for monitoring the training result and early stopping. It can be a
string or list of strings as names of predefined metric in XGBoost (See
XGBoost Parameters), one of the metrics in sklearn.metrics, or any
other user defined metric that looks like sklearn.metrics.
If custom objective is also provided, then custom metric should implement the
corresponding reverse link function.
Unlike the scoring parameter commonly used in scikit-learn, when a callable
object is provided, it’s assumed to be a cost function and by default XGBoost
will minimize the result during early stopping.
For advanced usage on Early stopping like directly choosing to maximize instead
of minimize, see xgboost.callback.EarlyStopping.
Activates early stopping. Validation metric needs to improve at least once in
every early_stopping_rounds round(s) to continue training. Requires at
least one item in eval_set in fit().
If early stopping occurs, the model will have two additional attributes:
best_score and best_iteration. These are used by the
predict() and apply() methods to determine the optimal
number of trees during inference. If users want to access the full model
(including trees built after early stopping), they can specify the
iteration_range in these inference methods. In addition, other utilities
like model plotting can also use the entire model.
If you prefer to discard the trees after best_iteration, consider using the
callback function xgboost.callback.EarlyStopping.
If there’s more than one item in eval_set, the last entry will be used for
early stopping. If there’s more than one metric in eval_metric, the last
metric will be used for early stopping.
List of callback functions that are applied at end of each iteration.
It is possible to use predefined callbacks by using
Callback API.
forparamsinparameters_grid:# be sure to (re)initialize the callbacks before each runcallbacks=[xgb.callback.LearningRateScheduler(custom_rates)]reg=xgboost.XGBRegressor(**params,callbacks=callbacks)reg.fit(X,y)
Keyword arguments for XGBoost Booster object. Full documentation of parameters
can be found here.
Attempting to set a parameter via the constructor args and **kwargs
dict simultaneously will result in a TypeError.
apply(X, iteration_range=None)
Return the predicted leaf every tree for each sample. If the model is trained
with early stopping, then best_iteration is used automatically.
Parameters:
X (Any) – Input features matrix. See Markers for a list of supported types.
X_leaves – For each datapoint x in X and for each tree, return the index of the
leaf x ends up in. Leaves are numbered within
[0;2**(self.max_depth+1)), possibly with gaps in the numbering.
The best iteration obtained by early stopping. This attribute is 0-based,
for instance if the best iteration is the first round, then best_iteration is 0.
array of shape [n_features] or [n_classes,n_features]
evals_result()
Return the evaluation results.
If eval_set is passed to the fit() function, you can call
evals_result() to get evaluation results for all passed eval_sets. When
eval_metric is also passed to the fit() function, the
evals_result will contain the eval_metrics passed to the fit()
function.
Feature importances property, return depends on importance_type
parameter. When model trained with multi-class/multi-label/multi-target dataset,
the feature importance is “averaged” over all targets. The “average” is defined
based on the importance type. For instance, if the importance type is
“total_gain”, then the score is sum of loss change for each split from all
trees.
Returns:
feature_importances_ (array of shape [n_features] except for multi-class)
linear model, which returns an array with shape (n_features, n_classes)
Note that calling fit() multiple times will cause the model object to be
re-fit from scratch. To resume training from a previous checkpoint, explicitly
pass xgb_model argument.
Input feature matrix. See Markers for a list of supported types.
When the tree_method is set to hist, internally, the
QuantileDMatrix will be used instead of the
for conserving memory. However, this has performance implications when the
device of input data is not matched with algorithm. For instance, if the
input is a numpy array on CPU but is used for training, then the
data is first processed on CPU then transferred to GPU.
get_booster()
Get the underlying xgboost Booster of this model.
This will raise an exception when fit was not called
Returns:
booster
Return type:
a xgboost booster of underlying model
get_metadata_routing()
Get metadata routing of this object.
Please check User Guide on how the routing
mechanism works.
Returns:
routing – A MetadataRequest encapsulating
routing information.
For tree-based model, the returned value is the base_score.
Returns:
intercept_
Return type:
array of shape (1,) or [n_classes]
load_model(fname)
Load the model from a file or a bytearray.
The model is saved in an XGBoost internal format which is universal among the
various XGBoost interfaces. Auxiliary attributes of the Python Booster object
(such as feature_names) are only saved when using JSON or UBJSON (default)
format. Also, parameters that are not part of the model (like metrics,
max_depth, etc) are not saved, see Model IO
for more info.
Predict with X. If the model is trained with early stopping, then
best_iteration is used automatically. The estimator uses
inplace_predict by default and falls back to using DMatrix if
devices between the data and the estimator don’t match.
Parameters:
X (Any) – Data to predict with. See Markers for a list of supported types.
output_margin (bool) – Whether to output the raw untransformed margin value.
validate_features (bool) – When this is True, validate that the Booster’s and data’s feature_names are
identical. Otherwise, it is assumed that the feature_names are the same.
base_margin (Any | None) – Global bias for each instance. See Intercept for details.
Predict the probability of each X example being of a given class. If the
model is trained with early stopping, then best_iteration is used
automatically. The estimator uses inplace_predict by default and falls back to
using DMatrix if devices between the data and the estimator don’t
match.
Parameters:
X (Any) – Feature matrix. See Markers for a list of supported types.
validate_features (bool) – When this is True, validate that the Booster’s and data’s feature_names are
identical. Otherwise, it is assumed that the feature_names are the same.
base_margin (Any | None) – Global bias for each instance. See Intercept for details.
iteration_range (Tuple[) – Specifies which layer of trees are used in prediction. For example, if a
random forest is trained with 100 rounds. Specifying , then only the forests built during [10, 20) (half open set) rounds are
used in this prediction.
save_model(fname)
Save the model to a file.
The model is saved in an XGBoost internal format which is universal among the
various XGBoost interfaces. Auxiliary attributes of the Python Booster object
(such as feature_names) are only saved when using JSON or UBJSON (default)
format. Also, parameters that are not part of the model (like metrics,
max_depth, etc) are not saved, see Model IO
for more info.
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:
X (array-like of shape (n_samples, n_features)) – Test samples.
y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – True labels for X.
sample_weight (array-like of shape (n_samples,), default=None) – Sample weights.
Returns:
score – Mean accuracy of self.predict(X) w.r.t. y.
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 .
set_params(**params)
Set the parameters of this estimator. Modification of the sklearn method to
allow unknown kwargs. This allows using the full range of xgboost
parameters that are not defined as member variables in sklearn grid
search.
Configure whether metadata should be requested to be passed to the predict_proba 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 predict_proba 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 predict_proba.
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.
Parameters:
base_margin (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for base_margin parameter in predict_proba.
iteration_range (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for iteration_range parameter in .
Configure whether metadata should be requested to be passed to the predict 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 predict 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 predict.
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.
Parameters:
base_margin (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for base_margin parameter in predict.
iteration_range (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for iteration_range parameter in .
set_score_request(*, sample_weight='$UNCHANGED$')
Configure whether metadata should be requested to be passed to the score 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 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.
Parameters:
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in score.
booster (Optional[str]) – Specify which booster to use: gbtree, gblinear or dart.
tree_method (Optional[str]) – Specify which tree method to use. Default to auto. If this parameter is set to
default, XGBoost will choose the most conservative option available. It’s
recommended to study this option from the parameters document tree method
n_jobs (Optional[int]) – Number of parallel threads used to run xgboost. When used with other
Scikit-Learn algorithms like grid search, you may choose which algorithm to
parallelize and balance the threads. Creating thread contention will
significantly slow down both algorithms.
gamma (Optional[float]) – (min_split_loss) Minimum loss reduction required to make a further partition on
a leaf node of the tree.
min_child_weight (Optional[float]) – Minimum sum of instance weight(hessian) needed in a child.
max_delta_step (Optional[float]) – Maximum delta step we allow each tree’s weight estimation to be.
subsample (Optional[float]) – Subsample ratio of the training instance.
missing (float) – Value in the data which needs to be present as a missing value. Default to
numpy.nan.
num_parallel_tree (Optional[int]) – Used for boosting random forest.
monotone_constraints (Union[Dict[str, int], str, NoneType]) – Constraint of variable monotonicity. See tutorial
for more information.
interaction_constraints (Union[str, List[Tuple[str]], NoneType]) – Constraints for interaction representing permitted interactions. The
constraints must be specified in the form of a nested list, e.g. [[0,1],[2,3,4]], where each inner list is a group of indices of features that are
allowed to interact with each other. See tutorial for more information
Used for specifying feature types without constructing a dataframe. See
the DMatrix for details.
feature_weights (Optional[ArrayLike]) – Weight for each feature, defines the probability of each feature being selected
when colsample is being used. All values must be greater than 0, otherwise a
ValueError is thrown.
A threshold for deciding whether XGBoost should use one-hot encoding based split
for categorical data. When number of categories is lesser than the threshold
then one-hot encoding is chosen, otherwise the categories will be partitioned
into children nodes. Also, enable_categorical needs to be set to have
categorical feature support. See Categorical Data and Parameters for Categorical Feature for details.
Maximum number of categories considered for each split. Used only by
partition-based splits for preventing over-fitting. Also, enable_categorical
needs to be set to have categorical feature support. See Categorical Data and Parameters for Categorical Feature for details.
The strategy used for training multi-target models, including multi-target
regression and multi-class classification. See Multiple Outputs for
more information.
Metric used for monitoring the training result and early stopping. It can be a
string or list of strings as names of predefined metric in XGBoost (See
XGBoost Parameters), one of the metrics in sklearn.metrics, or any
other user defined metric that looks like sklearn.metrics.
If custom objective is also provided, then custom metric should implement the
corresponding reverse link function.
Unlike the scoring parameter commonly used in scikit-learn, when a callable
object is provided, it’s assumed to be a cost function and by default XGBoost
will minimize the result during early stopping.
For advanced usage on Early stopping like directly choosing to maximize instead
of minimize, see xgboost.callback.EarlyStopping.
Activates early stopping. Validation metric needs to improve at least once in
every early_stopping_rounds round(s) to continue training. Requires at
least one item in eval_set in fit().
If early stopping occurs, the model will have two additional attributes:
best_score and best_iteration. These are used by the
predict() and apply() methods to determine the optimal
number of trees during inference. If users want to access the full model
(including trees built after early stopping), they can specify the
iteration_range in these inference methods. In addition, other utilities
like model plotting can also use the entire model.
If you prefer to discard the trees after best_iteration, consider using the
callback function xgboost.callback.EarlyStopping.
If there’s more than one item in eval_set, the last entry will be used for
early stopping. If there’s more than one metric in eval_metric, the last
metric will be used for early stopping.
List of callback functions that are applied at end of each iteration.
It is possible to use predefined callbacks by using
Callback API.
forparamsinparameters_grid:# be sure to (re)initialize the callbacks before each runcallbacks=[xgb.callback.LearningRateScheduler(custom_rates)]reg=xgboost.XGBRegressor(**params,callbacks=callbacks)reg.fit(X,y)
Keyword arguments for XGBoost Booster object. Full documentation of parameters
can be found here.
Attempting to set a parameter via the constructor args and **kwargs
dict simultaneously will result in a TypeError.
When fitting the model with the group parameter, your data need to be sorted
by the query group first. group is an array that contains the size of each
query group.
Similarly, when fitting the model with the qid parameter, the data should be
sorted according to query index and qid is an array that contains the query
index for each training sample.
For example, if your original data look like:
qid
label
features
1
0
x_1
1
1
x_2
1
then fit() method can be called with either group array as [3,4]
or with qid as [1,1,1,2,2,2,2], that is the qid column. Also, the
qid can be a special column of input X instead of a separated parameter, see
fit() for more info.
apply(X, iteration_range=None)
Return the predicted leaf every tree for each sample. If the model is trained
with early stopping, then best_iteration is used automatically.
Parameters:
X (Any) – Input features matrix. See Markers for a list of supported types.
X_leaves – For each datapoint x in X and for each tree, return the index of the
leaf x ends up in. Leaves are numbered within
[0;2**(self.max_depth+1)), possibly with gaps in the numbering.
The best iteration obtained by early stopping. This attribute is 0-based,
for instance if the best iteration is the first round, then best_iteration is 0.
array of shape [n_features] or [n_classes,n_features]
evals_result()
Return the evaluation results.
If eval_set is passed to the fit() function, you can call
evals_result() to get evaluation results for all passed eval_sets. When
eval_metric is also passed to the fit() function, the
evals_result will contain the eval_metrics passed to the fit()
function.
Feature importances property, return depends on importance_type
parameter. When model trained with multi-class/multi-label/multi-target dataset,
the feature importance is “averaged” over all targets. The “average” is defined
based on the importance type. For instance, if the importance type is
“total_gain”, then the score is sum of loss change for each split from all
trees.
Returns:
feature_importances_ (array of shape [n_features] except for multi-class)
linear model, which returns an array with shape (n_features, n_classes)
Note that calling fit() multiple times will cause the model object to be
re-fit from scratch. To resume training from a previous checkpoint, explicitly
pass xgb_model argument.
Feature matrix. See Markers for a list of supported types.
When this is a pandas.DataFrame or a cudf.DataFrame,
it may contain a special column called for specifying the query
index. Using a special column is the same as using the parameter,
except for being compatible with sklearn utility functions like
. The same convention
applies to the and .
get_booster()
Get the underlying xgboost Booster of this model.
This will raise an exception when fit was not called
Returns:
booster
Return type:
a xgboost booster of underlying model
get_metadata_routing()
Get metadata routing of this object.
Please check User Guide on how the routing
mechanism works.
Returns:
routing – A MetadataRequest encapsulating
routing information.
For tree-based model, the returned value is the base_score.
Returns:
intercept_
Return type:
array of shape (1,) or [n_classes]
load_model(fname)
Load the model from a file or a bytearray.
The model is saved in an XGBoost internal format which is universal among the
various XGBoost interfaces. Auxiliary attributes of the Python Booster object
(such as feature_names) are only saved when using JSON or UBJSON (default)
format. Also, parameters that are not part of the model (like metrics,
max_depth, etc) are not saved, see Model IO
for more info.
Predict with X. If the model is trained with early stopping, then
best_iteration is used automatically. The estimator uses
inplace_predict by default and falls back to using DMatrix if
devices between the data and the estimator don’t match.
Parameters:
X (Any) – Data to predict with. See Markers for a list of supported types.
output_margin (bool) – Whether to output the raw untransformed margin value.
validate_features (bool) – When this is True, validate that the Booster’s and data’s feature_names are
identical. Otherwise, it is assumed that the feature_names are the same.
base_margin (Any | None) – Global bias for each instance. See Intercept for details.
save_model(fname)
Save the model to a file.
The model is saved in an XGBoost internal format which is universal among the
various XGBoost interfaces. Auxiliary attributes of the Python Booster object
(such as feature_names) are only saved when using JSON or UBJSON (default)
format. Also, parameters that are not part of the model (like metrics,
max_depth, etc) are not saved, see Model IO
for more info.
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 .
set_params(**params)
Set the parameters of this estimator. Modification of the sklearn method to
allow unknown kwargs. This allows using the full range of xgboost
parameters that are not defined as member variables in sklearn grid
search.
Configure whether metadata should be requested to be passed to the predict 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 predict 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 predict.
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.
Parameters:
base_margin (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for base_margin parameter in predict.
iteration_range (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for iteration_range parameter in .
Parameters:
n_estimators (Optional[int]) – Number of trees in random forest to fit.
max_depth (Optional[int]) – Maximum tree depth for base learners.
max_leaves (Optional[int]) – Maximum number of leaves; 0 indicates no limit.
max_bin (Optional[int]) – If using histogram-based algorithm, maximum number of bins per feature
Specify the learning task and the corresponding learning objective or a custom
objective function to be used.
booster (Optional[str]) – Specify which booster to use: gbtree, gblinear or dart.
tree_method (Optional[str]) – Specify which tree method to use. Default to auto. If this parameter is set to
default, XGBoost will choose the most conservative option available. It’s
recommended to study this option from the parameters document tree method
n_jobs (Optional[int]) – Number of parallel threads used to run xgboost. When used with other
Scikit-Learn algorithms like grid search, you may choose which algorithm to
parallelize and balance the threads. Creating thread contention will
significantly slow down both algorithms.
gamma (Optional[float]) – (min_split_loss) Minimum loss reduction required to make a further partition on
a leaf node of the tree.
min_child_weight (Optional[float]) – Minimum sum of instance weight(hessian) needed in a child.
max_delta_step (Optional[float]) – Maximum delta step we allow each tree’s weight estimation to be.
subsample (Optional[float]) – Subsample ratio of the training instance.
missing (float) – Value in the data which needs to be present as a missing value. Default to
numpy.nan.
num_parallel_tree (Optional[int]) – Used for boosting random forest.
monotone_constraints (Union[Dict[str, int], str, NoneType]) – Constraint of variable monotonicity. See tutorial
for more information.
interaction_constraints (Union[str, List[Tuple[str]], NoneType]) – Constraints for interaction representing permitted interactions. The
constraints must be specified in the form of a nested list, e.g. [[0,1],[2,3,4]], where each inner list is a group of indices of features that are
allowed to interact with each other. See tutorial for more information
Used for specifying feature types without constructing a dataframe. See
the DMatrix for details.
feature_weights (Optional[ArrayLike]) – Weight for each feature, defines the probability of each feature being selected
when colsample is being used. All values must be greater than 0, otherwise a
ValueError is thrown.
A threshold for deciding whether XGBoost should use one-hot encoding based split
for categorical data. When number of categories is lesser than the threshold
then one-hot encoding is chosen, otherwise the categories will be partitioned
into children nodes. Also, enable_categorical needs to be set to have
categorical feature support. See Categorical Data and Parameters for Categorical Feature for details.
Maximum number of categories considered for each split. Used only by
partition-based splits for preventing over-fitting. Also, enable_categorical
needs to be set to have categorical feature support. See Categorical Data and Parameters for Categorical Feature for details.
The strategy used for training multi-target models, including multi-target
regression and multi-class classification. See Multiple Outputs for
more information.
Activates early stopping. Validation metric needs to improve at least once in
every early_stopping_rounds round(s) to continue training. Requires at
least one item in eval_set in fit().
If early stopping occurs, the model will have two additional attributes:
best_score and . These are used by the
and methods to determine the optimal
number of trees during inference. If users want to access the full model
(including trees built after early stopping), they can specify the
in these inference methods. In addition, other utilities
like model plotting can also use the entire model.
Keyword arguments for XGBoost Booster object. Full documentation of parameters
can be found here.
Attempting to set a parameter via the constructor args and **kwargs
dict simultaneously will result in a TypeError.
apply(X, iteration_range=None)
Return the predicted leaf every tree for each sample. If the model is trained
with early stopping, then best_iteration is used automatically.
Parameters:
X (Any) – Input features matrix. See Markers for a list of supported types.
X_leaves – For each datapoint x in X and for each tree, return the index of the
leaf x ends up in. Leaves are numbered within
[0;2**(self.max_depth+1)), possibly with gaps in the numbering.
The best iteration obtained by early stopping. This attribute is 0-based,
for instance if the best iteration is the first round, then best_iteration is 0.
array of shape [n_features] or [n_classes,n_features]
evals_result()
Return the evaluation results.
If eval_set is passed to the fit() function, you can call
evals_result() to get evaluation results for all passed eval_sets. When
eval_metric is also passed to the fit() function, the
evals_result will contain the eval_metrics passed to the fit()
function.
Feature importances property, return depends on importance_type
parameter. When model trained with multi-class/multi-label/multi-target dataset,
the feature importance is “averaged” over all targets. The “average” is defined
based on the importance type. For instance, if the importance type is
“total_gain”, then the score is sum of loss change for each split from all
trees.
Returns:
feature_importances_ (array of shape [n_features] except for multi-class)
linear model, which returns an array with shape (n_features, n_classes)
Note that calling fit() multiple times will cause the model object to be
re-fit from scratch. To resume training from a previous checkpoint, explicitly
pass xgb_model argument.
Input feature matrix. See Markers for a list of supported types.
When the tree_method is set to hist, internally, the
QuantileDMatrix will be used instead of the
for conserving memory. However, this has performance implications when the
device of input data is not matched with algorithm. For instance, if the
input is a numpy array on CPU but is used for training, then the
data is first processed on CPU then transferred to GPU.
get_booster()
Get the underlying xgboost Booster of this model.
This will raise an exception when fit was not called
Returns:
booster
Return type:
a xgboost booster of underlying model
get_metadata_routing()
Get metadata routing of this object.
Please check User Guide on how the routing
mechanism works.
Returns:
routing – A MetadataRequest encapsulating
routing information.
For tree-based model, the returned value is the base_score.
Returns:
intercept_
Return type:
array of shape (1,) or [n_classes]
load_model(fname)
Load the model from a file or a bytearray.
The model is saved in an XGBoost internal format which is universal among the
various XGBoost interfaces. Auxiliary attributes of the Python Booster object
(such as feature_names) are only saved when using JSON or UBJSON (default)
format. Also, parameters that are not part of the model (like metrics,
max_depth, etc) are not saved, see Model IO
for more info.
Predict with X. If the model is trained with early stopping, then
best_iteration is used automatically. The estimator uses
inplace_predict by default and falls back to using DMatrix if
devices between the data and the estimator don’t match.
Parameters:
X (Any) – Data to predict with. See Markers for a list of supported types.
output_margin (bool) – Whether to output the raw untransformed margin value.
validate_features (bool) – When this is True, validate that the Booster’s and data’s feature_names are
identical. Otherwise, it is assumed that the feature_names are the same.
base_margin (Any | None) – Global bias for each instance. See Intercept for details.
save_model(fname)
Save the model to a file.
The model is saved in an XGBoost internal format which is universal among the
various XGBoost interfaces. Auxiliary attributes of the Python Booster object
(such as feature_names) are only saved when using JSON or UBJSON (default)
format. Also, parameters that are not part of the model (like metrics,
max_depth, etc) are not saved, see Model IO
for more info.
The coefficient of determination, R2, is defined as
(1−vu), 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 R2 score of 0.0.
Parameters:
X (array-like of shape (n_samples, n_features)) – Test samples. For some estimators this may be a precomputed
kernel matrix or a list of generic objects instead with shape
(n_samples,n_samples_fitted), where n_samples_fitted
is the number of samples used in the fitting for the estimator.
y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – True values for X.
sample_weight (array-like of shape (n_samples,)) – Sample weights.
Notes
The R2 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 .
set_params(**params)
Set the parameters of this estimator. Modification of the sklearn method to
allow unknown kwargs. This allows using the full range of xgboost
parameters that are not defined as member variables in sklearn grid
search.
Configure whether metadata should be requested to be passed to the predict 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 predict 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 predict.
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.
Parameters:
base_margin (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for base_margin parameter in predict.
iteration_range (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for iteration_range parameter in .
set_score_request(*, sample_weight='$UNCHANGED$')
Configure whether metadata should be requested to be passed to the score 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 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.
Parameters:
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in score.
Specify the learning task and the corresponding learning objective or a custom
objective function to be used.
booster (Optional[str]) – Specify which booster to use: gbtree, gblinear or dart.
tree_method (Optional[str]) – Specify which tree method to use. Default to auto. If this parameter is set to
default, XGBoost will choose the most conservative option available. It’s
recommended to study this option from the parameters document tree method
n_jobs (Optional[int]) – Number of parallel threads used to run xgboost. When used with other
Scikit-Learn algorithms like grid search, you may choose which algorithm to
parallelize and balance the threads. Creating thread contention will
significantly slow down both algorithms.
gamma (Optional[float]) – (min_split_loss) Minimum loss reduction required to make a further partition on
a leaf node of the tree.
min_child_weight (Optional[float]) – Minimum sum of instance weight(hessian) needed in a child.
max_delta_step (Optional[float]) – Maximum delta step we allow each tree’s weight estimation to be.
subsample (Optional[float]) – Subsample ratio of the training instance.
missing (float) – Value in the data which needs to be present as a missing value. Default to
numpy.nan.
num_parallel_tree (Optional[int]) – Used for boosting random forest.
monotone_constraints (Union[Dict[str, int], str, NoneType]) – Constraint of variable monotonicity. See tutorial
for more information.
interaction_constraints (Union[str, List[Tuple[str]], NoneType]) – Constraints for interaction representing permitted interactions. The
constraints must be specified in the form of a nested list, e.g. [[0,1],[2,3,4]], where each inner list is a group of indices of features that are
allowed to interact with each other. See tutorial for more information
Used for specifying feature types without constructing a dataframe. See
the DMatrix for details.
feature_weights (Optional[ArrayLike]) – Weight for each feature, defines the probability of each feature being selected
when colsample is being used. All values must be greater than 0, otherwise a
ValueError is thrown.
A threshold for deciding whether XGBoost should use one-hot encoding based split
for categorical data. When number of categories is lesser than the threshold
then one-hot encoding is chosen, otherwise the categories will be partitioned
into children nodes. Also, enable_categorical needs to be set to have
categorical feature support. See Categorical Data and Parameters for Categorical Feature for details.
Maximum number of categories considered for each split. Used only by
partition-based splits for preventing over-fitting. Also, enable_categorical
needs to be set to have categorical feature support. See Categorical Data and Parameters for Categorical Feature for details.
The strategy used for training multi-target models, including multi-target
regression and multi-class classification. See Multiple Outputs for
more information.
Activates early stopping. Validation metric needs to improve at least once in
every early_stopping_rounds round(s) to continue training. Requires at
least one item in eval_set in fit().
If early stopping occurs, the model will have two additional attributes:
best_score and . These are used by the
and methods to determine the optimal
number of trees during inference. If users want to access the full model
(including trees built after early stopping), they can specify the
in these inference methods. In addition, other utilities
like model plotting can also use the entire model.
Keyword arguments for XGBoost Booster object. Full documentation of parameters
can be found here.
Attempting to set a parameter via the constructor args and **kwargs
dict simultaneously will result in a TypeError.
apply(X, iteration_range=None)
Return the predicted leaf every tree for each sample. If the model is trained
with early stopping, then best_iteration is used automatically.
Parameters:
X (Any) – Input features matrix. See Markers for a list of supported types.
X_leaves – For each datapoint x in X and for each tree, return the index of the
leaf x ends up in. Leaves are numbered within
[0;2**(self.max_depth+1)), possibly with gaps in the numbering.
The best iteration obtained by early stopping. This attribute is 0-based,
for instance if the best iteration is the first round, then best_iteration is 0.
array of shape [n_features] or [n_classes,n_features]
evals_result()
Return the evaluation results.
If eval_set is passed to the fit() function, you can call
evals_result() to get evaluation results for all passed eval_sets. When
eval_metric is also passed to the fit() function, the
evals_result will contain the eval_metrics passed to the fit()
function.
Feature importances property, return depends on importance_type
parameter. When model trained with multi-class/multi-label/multi-target dataset,
the feature importance is “averaged” over all targets. The “average” is defined
based on the importance type. For instance, if the importance type is
“total_gain”, then the score is sum of loss change for each split from all
trees.
Returns:
feature_importances_ (array of shape [n_features] except for multi-class)
linear model, which returns an array with shape (n_features, n_classes)
Note that calling fit() multiple times will cause the model object to be
re-fit from scratch. To resume training from a previous checkpoint, explicitly
pass xgb_model argument.
Input feature matrix. See Markers for a list of supported types.
When the tree_method is set to hist, internally, the
QuantileDMatrix will be used instead of the
for conserving memory. However, this has performance implications when the
device of input data is not matched with algorithm. For instance, if the
input is a numpy array on CPU but is used for training, then the
data is first processed on CPU then transferred to GPU.
get_booster()
Get the underlying xgboost Booster of this model.
This will raise an exception when fit was not called
Returns:
booster
Return type:
a xgboost booster of underlying model
get_metadata_routing()
Get metadata routing of this object.
Please check User Guide on how the routing
mechanism works.
Returns:
routing – A MetadataRequest encapsulating
routing information.
For tree-based model, the returned value is the base_score.
Returns:
intercept_
Return type:
array of shape (1,) or [n_classes]
load_model(fname)
Load the model from a file or a bytearray.
The model is saved in an XGBoost internal format which is universal among the
various XGBoost interfaces. Auxiliary attributes of the Python Booster object
(such as feature_names) are only saved when using JSON or UBJSON (default)
format. Also, parameters that are not part of the model (like metrics,
max_depth, etc) are not saved, see Model IO
for more info.
Predict with X. If the model is trained with early stopping, then
best_iteration is used automatically. The estimator uses
inplace_predict by default and falls back to using DMatrix if
devices between the data and the estimator don’t match.
Parameters:
X (Any) – Data to predict with. See Markers for a list of supported types.
output_margin (bool) – Whether to output the raw untransformed margin value.
validate_features (bool) – When this is True, validate that the Booster’s and data’s feature_names are
identical. Otherwise, it is assumed that the feature_names are the same.
base_margin (Any | None) – Global bias for each instance. See Intercept for details.
Predict the probability of each X example being of a given class. If the
model is trained with early stopping, then best_iteration is used
automatically. The estimator uses inplace_predict by default and falls back to
using DMatrix if devices between the data and the estimator don’t
match.
Parameters:
X (Any) – Feature matrix. See Markers for a list of supported types.
validate_features (bool) – When this is True, validate that the Booster’s and data’s feature_names are
identical. Otherwise, it is assumed that the feature_names are the same.
base_margin (Any | None) – Global bias for each instance. See Intercept for details.
iteration_range (Tuple[) – Specifies which layer of trees are used in prediction. For example, if a
random forest is trained with 100 rounds. Specifying , then only the forests built during [10, 20) (half open set) rounds are
used in this prediction.
save_model(fname)
Save the model to a file.
The model is saved in an XGBoost internal format which is universal among the
various XGBoost interfaces. Auxiliary attributes of the Python Booster object
(such as feature_names) are only saved when using JSON or UBJSON (default)
format. Also, parameters that are not part of the model (like metrics,
max_depth, etc) are not saved, see Model IO
for more info.
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:
X (array-like of shape (n_samples, n_features)) – Test samples.
y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – True labels for X.
sample_weight (array-like of shape (n_samples,), default=None) – Sample weights.
Returns:
score – Mean accuracy of self.predict(X) w.r.t. y.
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 .
set_params(**params)
Set the parameters of this estimator. Modification of the sklearn method to
allow unknown kwargs. This allows using the full range of xgboost
parameters that are not defined as member variables in sklearn grid
search.
Configure whether metadata should be requested to be passed to the predict_proba 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 predict_proba 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 predict_proba.
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.
Parameters:
base_margin (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for base_margin parameter in predict_proba.
iteration_range (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for iteration_range parameter in .
Configure whether metadata should be requested to be passed to the predict 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 predict 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 predict.
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.
Parameters:
base_margin (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for base_margin parameter in predict.
iteration_range (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for iteration_range parameter in .
set_score_request(*, sample_weight='$UNCHANGED$')
Configure whether metadata should be requested to be passed to the score 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 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.
Parameters:
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in score.
xlabel (str) – X axis title label. To disable, pass None.
ylabel (str) – Y axis title label. To disable, pass None.
fmap (str | PathLike) – The name of feature map file.
show_values (bool) – Show values on plot. To disable, pass False.
values_format (str) – Format string for values. “v” will be replaced by the value of the feature
importance. e.g. Pass “{v:.2f}” in order to limit the number of digits after
the decimal point to two, for each value printed on the graph.
Convert specified tree to graphviz instance. IPython can automatically plot
the returned graphviz instance. Otherwise, you should call .render() method
of the returned graphviz instance.
Parameters:
booster (Booster | XGBModel) – Booster or XGBModel instance
fmap (str | PathLike) – The name of feature map file
metric_name (str | None) – Name of metric that is used for early stopping.
data_name (str | None) – Name of dataset that is used for early stopping.
maximize (bool | None) – Whether to maximize evaluation metric. None means auto (discouraged).
save_best (bool | None) – Whether training should return the best model or the last model. If set to
True, it will only keep the boosting rounds up to the detected best iteration,
discarding the ones that come after. This is only supported with tree methods
(not gblinear). Also, the cv function doesn’t return a model, the parameter
is not applicable.
SparkXGBClassifier doesn’t support setting base_margin explicitly as well, but
support another param called base_margin_col. see doc below for more details.
SparkXGBClassifier doesn’t support setting output_margin, but we can get output
margin from the raw prediction column. See raw_prediction_col param doc below for
more details.
SparkXGBClassifier doesn’t support validate_features and output_margin param.
SparkXGBClassifier doesn’t support setting nthread xgboost param, instead, the
nthread param for each xgboost worker will be set equal to spark.task.cpus
config value.
Parameters:
features_col (str | List[str]) – When the value is string, it requires the features column name to be vector type.
When the value is a list of string, it requires all the feature columns to be numeric types.
label_col (str) – Label column name. Default to “label”.
prediction_col (str) – Prediction column name. Default to “prediction”
probability_col (str) – Column name for predicted class conditional probabilities. Default to probabilityCol
raw_prediction_col (str) – The output_margin=True is implicitly supported by the
rawPredictionCol output column, which is always returned with the predicted margin
values.
validation_indicator_col (str | None) – For params related to xgboost.XGBClassifier training with
evaluation dataset’s supervision,
set xgboost.spark.SparkXGBClassifier.validation_indicator_col
parameter instead of setting the eval_set parameter in xgboost.XGBClassifier
fit method.
weight_col (str | None) – To specify the weight of the training and validation dataset, set
xgboost.spark.SparkXGBClassifier.weight_col parameter instead of setting
sample_weight and sample_weight_eval_set parameter in xgboost.XGBClassifier
fit method.
base_margin_col (str | None) – To specify the base margins of the training and validation
dataset, set xgboost.spark.SparkXGBClassifier.base_margin_col parameter
instead of setting base_margin and base_margin_eval_set in the
xgboost.XGBClassifier fit method.
num_workers (int) – How many XGBoost workers to be used to train.
Each XGBoost worker corresponds to one spark task.
Device for XGBoost workers, available options are cpu, cuda, and gpu.
force_repartition (bool) – Boolean value to specify if forcing the input dataset to be repartitioned
before XGBoost training.
repartition_random_shuffle (bool) – Boolean value to specify if randomly shuffling the dataset when repartitioning is required.
enable_sparse_data_optim (bool) – Boolean value to specify if enabling sparse data optimization, if True,
Xgboost DMatrix object will be constructed from sparse matrix instead of
dense matrix.
launch_tracker_on_driver (bool) – Boolean value to indicate whether the tracker should be launched on the driver side or
the executor side.
coll_cfg (Config | None) – The collective configuration. See Config
Creates a copy of this instance with the same uid and some
extra params. The default implementation creates a
shallow copy using copy.copy(), and then copies the
embedded and extra parameters over and returns the copy.
Subclasses should override this method if the default approach
is not sufficient.
Parameters:
extra (dict, optional) – Extra parameters to copy to the new instance
self (P)
Returns:
Copy of this instance
Return type:
Params
explainParam(param)
Explains a single param and returns its name, doc, and optional
default value and user-supplied value in a string.
Extracts the embedded default param values and user-supplied
values, and then merges them with extra values from input into
a flat param map, where the latter value is used if there exist
conflicts, i.e., with ordering: default param values <
user-supplied values < extra.
params (dict or list or tuple, optional) – an optional param map that overrides embedded params. If a list/tuple of
param maps is given, this calls fit on each param map and returns a list of
models.
Returns:
fitted model(s)
Return type:
Transformer or a list of Transformer
fitMultiple(dataset, paramMaps)
Fits a model to the input dataset for each param map in paramMaps.
A thread safe iterable which contains one model for each param map. Each
call to next(modelIterator) will return (index, model) where model was fit
using paramMaps[index]. index values may not be sequential.
Return type:
_FitMultipleIterator
getFeaturesCol()
Gets the value of featuresCol or its default value.
Creates a copy of this instance with the same uid and some
extra params. The default implementation creates a
shallow copy using copy.copy(), and then copies the
embedded and extra parameters over and returns the copy.
Subclasses should override this method if the default approach
is not sufficient.
Parameters:
extra (dict, optional) – Extra parameters to copy to the new instance
self (P)
Returns:
Copy of this instance
Return type:
Params
explainParam(param)
Explains a single param and returns its name, doc, and optional
default value and user-supplied value in a string.
Extracts the embedded default param values and user-supplied
values, and then merges them with extra values from input into
a flat param map, where the latter value is used if there exist
conflicts, i.e., with ordering: default param values <
user-supplied values < extra.
SparkXGBRegressor is a PySpark ML estimator. It implements the XGBoost regression
algorithm based on XGBoost python library, and it can be used in PySpark Pipeline
and PySpark ML meta algorithms like
- CrossValidator/
- TrainValidationSplit/
- OneVsRest
SparkXGBRegressor doesn’t support setting base_margin explicitly as well, but
support another param called base_margin_col. see doc below for more details.
SparkXGBRegressor doesn’t support validate_features and output_margin param.
SparkXGBRegressor doesn’t support setting nthread xgboost param, instead, the
nthread param for each xgboost worker will be set equal to spark.task.cpus
config value.
Parameters:
features_col (str | List[str]) – When the value is string, it requires the features column name to be vector type.
When the value is a list of string, it requires all the feature columns to be numeric types.
label_col (str) – Label column name. Default to “label”.
prediction_col (str) – Prediction column name. Default to “prediction”
Creates a copy of this instance with the same uid and some
extra params. The default implementation creates a
shallow copy using copy.copy(), and then copies the
embedded and extra parameters over and returns the copy.
Subclasses should override this method if the default approach
is not sufficient.
Parameters:
extra (dict, optional) – Extra parameters to copy to the new instance
self (P)
Returns
explainParam(param)
Explains a single param and returns its name, doc, and optional
default value and user-supplied value in a string.
Extracts the embedded default param values and user-supplied
values, and then merges them with extra values from input into
a flat param map, where the latter value is used if there exist
conflicts, i.e., with ordering: default param values <
user-supplied values < extra.
params () – an optional param map that overrides embedded params. If a list/tuple of
param maps is given, this calls fit on each param map and returns a list of
models.
fitMultiple(dataset, paramMaps)
Fits a model to the input dataset for each param map in paramMaps.
Creates a copy of this instance with the same uid and some
extra params. The default implementation creates a
shallow copy using copy.copy(), and then copies the
embedded and extra parameters over and returns the copy.
Subclasses should override this method if the default approach
is not sufficient.
Parameters:
extra (dict, optional) – Extra parameters to copy to the new instance
self (P)
Returns:
Copy of this instance
Return type:
Params
explainParam(param)
Explains a single param and returns its name, doc, and optional
default value and user-supplied value in a string.
Extracts the embedded default param values and user-supplied
values, and then merges them with extra values from input into
a flat param map, where the latter value is used if there exist
conflicts, i.e., with ordering: default param values <
user-supplied values < extra.
SparkXGBRanker is a PySpark ML estimator. It implements the XGBoost
ranking algorithm based on XGBoost python library, and it can be used in
PySpark Pipeline and PySpark ML meta algorithms like
CrossValidator/
TrainValidationSplit/
OneVsRest
SparkXGBRanker doesn’t support setting base_margin explicitly as well, but support
another param called base_margin_col. see doc below for more details.
SparkXGBRanker doesn’t support setting output_margin, but we can get output margin
from the raw prediction column. See raw_prediction_col param doc below for more
details.
SparkXGBRanker doesn’t support validate_features and output_margin param.
SparkXGBRanker doesn’t support setting nthread xgboost param, instead, the
nthread param for each xgboost worker will be set equal to spark.task.cpus
config value.
Parameters:
features_col (str | List[str]) – When the value is string, it requires the features column name to be vector type.
When the value is a list of string, it requires all the feature columns to be numeric types.
label_col (str) – Label column name. Default to “label”.
prediction_col (str) – Prediction column name. Default to “prediction”
Creates a copy of this instance with the same uid and some
extra params. The default implementation creates a
shallow copy using copy.copy(), and then copies the
embedded and extra parameters over and returns the copy.
Subclasses should override this method if the default approach
is not sufficient.
Parameters:
extra (dict, optional) – Extra parameters to copy to the new instance
self (P)
Returns
explainParam(param)
Explains a single param and returns its name, doc, and optional
default value and user-supplied value in a string.
Extracts the embedded default param values and user-supplied
values, and then merges them with extra values from input into
a flat param map, where the latter value is used if there exist
conflicts, i.e., with ordering: default param values <
user-supplied values < extra.
params () – an optional param map that overrides embedded params. If a list/tuple of
param maps is given, this calls fit on each param map and returns a list of
models.
fitMultiple(dataset, paramMaps)
Fits a model to the input dataset for each param map in paramMaps.
Creates a copy of this instance with the same uid and some
extra params. The default implementation creates a
shallow copy using copy.copy(), and then copies the
embedded and extra parameters over and returns the copy.
Subclasses should override this method if the default approach
is not sufficient.
Parameters:
extra (dict, optional) – Extra parameters to copy to the new instance
self (P)
Returns:
Copy of this instance
Return type:
Params
explainParam(param)
Explains a single param and returns its name, doc, and optional
default value and user-supplied value in a string.
Extracts the embedded default param values and user-supplied
values, and then merges them with extra values from input into
a flat param map, where the latter value is used if there exist
conflicts, i.e., with ordering: default param values <
user-supplied values < extra.
port (int) – The port this tracker should listen to. XGBoost can query an available port from
the OS, this configuration is useful for restricted network environments.
How to sort the workers for rank assignment. The default is host, but users can
set the DMLC_TASK_ID via arguments of init() and
obtain deterministic rank assignment through sorting by task name. Available
options are:
Timeout for constructing (bootstrap) and shutting down the communication group,
doesn’t apply to communication when the group is up and running.
The timeout value should take the time of data loading and pre-processing into
account, due to potential lazy execution. By default the Tracker doesn’t have
any timeout to avoid pre-mature aborting.
The wait_for() method has a different timeout parameter that can stop
the tracker even if the tracker is still being used. A value error is raised
when timeout is reached.
Data source of DMatrix. See Markers for a list of supported input
types.
Note that, if passing an iterator, it will cache data on disk, and note
that fields like label will be concatenated in-memory from multiple
calls to the iterator.
Set types for features. If data is a DataFrame type and passing
enable_categorical=True, the types will be deduced automatically from the
column types.
Otherwise, one can pass a list-like input with the same length as number of
columns in data, with the following possible values:
”c”, which represents categorical columns.
”q”, which represents numeric columns.
”int”, which represents integer columns.
”i”, which represents boolean columns.
Note that, while categorical types are treated differently from the rest for
model fitting purposes, the other types do not influence the generated
model, but have effects in other functionalities such as feature
importances.
For categorical features, the input is assumed to be preprocessed and
encoded by the users. The encoding can be done via
sklearn.preprocessing.OrdinalEncoder or pandas dataframe
.cat.codes method. This is useful when users want to specify categorical
features without having to construct a dataframe as input.
Alternatively, user can pass a Categories object
returned from previous training as a reference for re-coding. One can obtain
the reference with the get_categories() from the previous training
DMatrix or the Booster. This feature is experimental.
nthread (int | None) – Number of threads to use for loading data when parallelization is
applicable. If -1, uses maximum threads available on the system.
group (Any | None) – Group size for all ranking group.
qid (Any | None) – Query ID for data samples, used for ranking.
label_lower_bound (Any | None) – Lower bound for survival training.
label_upper_bound (Any | None) – Upper bound for survival training.
feature_weights (Any | None) – Set feature weights for column sampling.
Experimental support of specializing for categorical features. See
Categorical Data for more info.
If passing True and data is a data frame (from supported libraries such
as Pandas, Modin, polars, and cuDF), The DMatrix recognizes categorical
columns and automatically set the feature_types parameter. If data is
not a data frame, this argument is ignored.
If passing False and data is a data frame with categorical columns, it
will result in an error.
See notes in the DataIter for consistency requirement when the
input is an iterator.
XGBoost can remember the encoding of categories when the input is a
dataframe.
prediction – The prediction result. When input data is on GPU, prediction result is
stored in a cupy array.
Return type:
numpy.ndarray/cupy.ndarray
bool
pred_contribs (bool) – When this is True the output will be a matrix of size (nsample,
nfeats + 1) with each record indicating the feature contributions
(SHAP values) for that prediction. The sum of all feature
contributions is equal to the raw untransformed margin value of the
prediction. Note the final column is the bias term.
approx_contribs (bool) – Approximate the contributions of each feature. Used when pred_contribs
or pred_interactions is set to True. Changing the default of this
parameter (False) is not recommended.
pred_interactions (bool) – When this is True the output will be a matrix of size (nsample,
nfeats + 1, nfeats + 1) indicating the SHAP interaction values for
each pair of features. The sum of each row (or column) of the
interaction values equals the corresponding SHAP value (from
pred_contribs), and the sum of the entire matrix equals the raw
untransformed margin value of the prediction. Note the last row and
column correspond to the bias term.
validate_features (bool) – When this is True, validate that the Booster’s and data’s
feature_names are identical. Otherwise, it is assumed that the
feature_names are the same.
Whether the prediction value is used for training. This can effect dart
booster, which performs dropouts during training iterations but use all
trees for inference. If you want to obtain result with dropouts, set this
parameter to True. Also, the parameter is set to true when obtaining
prediction for custom objective function.
Specifies which layer of trees are used in prediction. For example, if a
random forest is trained with 100 rounds. Specifying iteration_range=(10,
20), then only the forests built during [10, 20) (half open set) rounds are
used in this prediction.
When set to True, output shape is invariant to whether classification is
used. For both value and margin prediction, the output shape is (n_samples,
n_groups), n_groups == 1 when multi-class is not used. Default to False, in
which case the output shape can be (n_samples, ) if multi-class is not used.
Returns:
prediction
Return type:
numpy array
]),
categories
=
categories
)
x1
[
"a"
]
=
pd
.
Categorical
.
from_codes
(
codes
=
np
.
array
([
1
,
2
]),
categories
=
categories
)
xgb
.
callback
.
LearningRateScheduler
(
custom_rates
)]
xgboost
.
train
(
params
,
Xy
,
callbacks
=
callbacks
)
mean_absolute_error
,
)
reg
.
fit
(
X
,
y
,
eval_set
=
[(
X
,
y
)])
fit
eval_set (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for eval_set parameter in fit.
feature_weights (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for feature_weights parameter in fit.
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in fit.
sample_weight_eval_set (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight_eval_set parameter in fit.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in fit.
xgb_model (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for xgb_model parameter in fit.
base_margin (Any | None) – Global bias for each instance. See Intercept for details.
eval_set (Sequence[Tuple[Any, Any]] | None) – A list of (X, y) tuple pairs to use as validation sets, for which
metrics will be computed.
Validation metrics will help us track the performance of the model.
verbose (bool | int | None) – If verbose is True and an evaluation set is used, the evaluation metric
measured on the validation set is printed to stdout at each boosting stage.
If verbose is an integer, the evaluation metric is printed at each
verbose boosting stage. The last boosting stage / the boosting stage found
by using early_stopping_rounds is also printed.
xgb_model (Booster | str | XGBModel | None) – file name of stored XGBoost model or ‘Booster’ instance XGBoost model to be
loaded before training (allows training continuation).
sample_weight_eval_set (Sequence[Any] | None) – A list of the form [L_1, L_2, …, L_n], where each L_i is an array like
object storing instance weights for the i-th validation set.
base_margin_eval_set (Sequence[Any] | None) – A list of the form [M_1, M_2, …, M_n], where each M_i is an array like
object storing base margin for the i-th validation set.
Specifies which layer of trees are used in prediction. For example, if a
random forest is trained with 100 rounds. Specifying iteration_range=(10,20), then only the forests built during [10, 20) (half open set) rounds
are used in this prediction.
a numpy array of shape array-like of shape (n_samples, n_classes) with the
probability of each data example being of a given class.
Return type:
prediction
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.
Parameters:
base_margin (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for base_margin parameter in fit.
base_margin_eval_set (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for base_margin_eval_set parameter in fit.
eval_set (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for eval_set parameter in fit.
feature_weights (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for feature_weights parameter in fit.
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in fit.
sample_weight_eval_set (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight_eval_set parameter in fit.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in fit.
xgb_model (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for xgb_model parameter in fit.
validate_features (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for validate_features parameter in predict_proba.
output_margin (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for output_margin parameter in predict.
validate_features (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for validate_features parameter in predict.
When the tree_method is set to hist, internally, the
QuantileDMatrix will be used instead of the DMatrix
for conserving memory. However, this has performance implications when the
device of input data is not matched with algorithm. For instance, if the
input is a numpy array on CPU but cuda is used for training, then the
data is first processed on CPU then transferred to GPU.
group (Any | None) – Size of each query group of training data. Should have as many elements as
the query groups in the training data. If this is set to None, then user
must provide qid.
qid (Any | None) – Query ID for each training sample. Should have the size of n_samples. If
this is set to None, then user must provide group or a special column in X.
base_margin (Any | None) – Global bias for each instance. See Intercept for details.
eval_set (Sequence[Tuple[Any, Any]] | None) – A list of (X, y) tuple pairs to use as validation sets, for which
metrics will be computed.
Validation metrics will help us track the performance of the model.
eval_group (Sequence[Any] | None) – A list in which eval_group[i] is the list containing the sizes of all
query groups in the i-th pair in eval_set.
eval_qid (Sequence[Any] | None) – A list in which eval_qid[i] is the array containing query ID of i-th
pair in eval_set. The special column convention in X applies to
validation datasets as well.
verbose (bool | int | None) – If verbose is True and an evaluation set is used, the evaluation metric
measured on the validation set is printed to stdout at each boosting stage.
If verbose is an integer, the evaluation metric is printed at each
verbose boosting stage. The last boosting stage / the boosting stage found
by using early_stopping_rounds is also printed.
xgb_model (Booster | str | XGBModel | None) – file name of stored XGBoost model or ‘Booster’ instance XGBoost model to be
loaded before training (allows training continuation).
A list of the form [L_1, L_2, …, L_n], where each L_i is a list of
group weights on the i-th validation set.
base_margin_eval_set (Sequence[Any] | None) – A list of the form [M_1, M_2, …, M_n], where each M_i is an array like
object storing base margin for the i-th validation set.
feature_weights (Any | None) – Weight for each feature, defines the probability of each feature being
selected when colsample is being used. All values must be greater than 0,
otherwise a ValueError is thrown.
Specifies which layer of trees are used in prediction. For example, if a
random forest is trained with 100 rounds. Specifying iteration_range=(10,20), then only the forests built during [10, 20) (half open set) rounds
are used in this prediction.
Return type:
prediction
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.
Parameters:
base_margin (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for base_margin parameter in fit.
base_margin_eval_set (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for base_margin_eval_set parameter in fit.
eval_group (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for eval_group parameter in fit.
eval_qid (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for eval_qid parameter in fit.
eval_set (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for eval_set parameter in fit.
feature_weights (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for feature_weights parameter in fit.
group (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for group parameter in fit.
qid (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for qid parameter in fit.
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in fit.
sample_weight_eval_set (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight_eval_set parameter in fit.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in fit.
xgb_model (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for xgb_model parameter in fit.
output_margin (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for output_margin parameter in predict.
validate_features (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for validate_features parameter in predict.
Metric used for monitoring the training result and early stopping. It can be a
string or list of strings as names of predefined metric in XGBoost (See
XGBoost Parameters), one of the metrics in sklearn.metrics, or any
other user defined metric that looks like sklearn.metrics.
If custom objective is also provided, then custom metric should implement the
corresponding reverse link function.
Unlike the scoring parameter commonly used in scikit-learn, when a callable
object is provided, it’s assumed to be a cost function and by default XGBoost
will minimize the result during early stopping.
For advanced usage on Early stopping like directly choosing to maximize instead
of minimize, see xgboost.callback.EarlyStopping.
If you prefer to discard the trees after best_iteration, consider using the
callback function xgboost.callback.EarlyStopping.
If there’s more than one item in eval_set, the last entry will be used for
early stopping. If there’s more than one metric in eval_metric, the last
metric will be used for early stopping.
The value of the second derivative for each sample point
Note that, if the custom objective produces negative values for
the Hessian, these will be clipped. If the objective is non-convex,
one might also consider using the expected Hessian (Fisher
information) instead.
base_margin (Any | None) – Global bias for each instance. See Intercept for details.
eval_set (Sequence[Tuple[Any, Any]] | None) – A list of (X, y) tuple pairs to use as validation sets, for which
metrics will be computed.
Validation metrics will help us track the performance of the model.
verbose (bool | int | None) – If verbose is True and an evaluation set is used, the evaluation metric
measured on the validation set is printed to stdout at each boosting stage.
If verbose is an integer, the evaluation metric is printed at each
verbose boosting stage. The last boosting stage / the boosting stage found
by using early_stopping_rounds is also printed.
xgb_model (Booster | str | XGBModel | None) – file name of stored XGBoost model or ‘Booster’ instance XGBoost model to be
loaded before training (allows training continuation).
sample_weight_eval_set (Sequence[Any] | None) – A list of the form [L_1, L_2, …, L_n], where each L_i is an array like
object storing instance weights for the i-th validation set.
base_margin_eval_set (Sequence[Any] | None) – A list of the form [M_1, M_2, …, M_n], where each M_i is an array like
object storing base margin for the i-th validation set.
Specifies which layer of trees are used in prediction. For example, if a
random forest is trained with 100 rounds. Specifying iteration_range=(10,20), then only the forests built during [10, 20) (half open set) rounds
are used in this prediction.
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.
Parameters:
base_margin (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for base_margin parameter in fit.
base_margin_eval_set (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for base_margin_eval_set parameter in fit.
eval_set (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for eval_set parameter in fit.
feature_weights (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for feature_weights parameter in fit.
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in fit.
sample_weight_eval_set (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight_eval_set parameter in fit.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in fit.
xgb_model (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for xgb_model parameter in fit.
output_margin (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for output_margin parameter in predict.
validate_features (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for validate_features parameter in predict.
Metric used for monitoring the training result and early stopping. It can be a
string or list of strings as names of predefined metric in XGBoost (See
XGBoost Parameters), one of the metrics in sklearn.metrics, or any
other user defined metric that looks like sklearn.metrics.
If custom objective is also provided, then custom metric should implement the
corresponding reverse link function.
Unlike the scoring parameter commonly used in scikit-learn, when a callable
object is provided, it’s assumed to be a cost function and by default XGBoost
will minimize the result during early stopping.
For advanced usage on Early stopping like directly choosing to maximize instead
of minimize, see xgboost.callback.EarlyStopping.
If you prefer to discard the trees after best_iteration, consider using the
callback function xgboost.callback.EarlyStopping.
If there’s more than one item in eval_set, the last entry will be used for
early stopping. If there’s more than one metric in eval_metric, the last
metric will be used for early stopping.
The value of the second derivative for each sample point
Note that, if the custom objective produces negative values for
the Hessian, these will be clipped. If the objective is non-convex,
one might also consider using the expected Hessian (Fisher
information) instead.
base_margin (Any | None) – Global bias for each instance. See Intercept for details.
eval_set (Sequence[Tuple[Any, Any]] | None) – A list of (X, y) tuple pairs to use as validation sets, for which
metrics will be computed.
Validation metrics will help us track the performance of the model.
verbose (bool | int | None) – If verbose is True and an evaluation set is used, the evaluation metric
measured on the validation set is printed to stdout at each boosting stage.
If verbose is an integer, the evaluation metric is printed at each
verbose boosting stage. The last boosting stage / the boosting stage found
by using early_stopping_rounds is also printed.
xgb_model (Booster | str | XGBModel | None) – file name of stored XGBoost model or ‘Booster’ instance XGBoost model to be
loaded before training (allows training continuation).
sample_weight_eval_set (Sequence[Any] | None) – A list of the form [L_1, L_2, …, L_n], where each L_i is an array like
object storing instance weights for the i-th validation set.
base_margin_eval_set (Sequence[Any] | None) – A list of the form [M_1, M_2, …, M_n], where each M_i is an array like
object storing base margin for the i-th validation set.
Specifies which layer of trees are used in prediction. For example, if a
random forest is trained with 100 rounds. Specifying iteration_range=(10,20), then only the forests built during [10, 20) (half open set) rounds
are used in this prediction.
a numpy array of shape array-like of shape (n_samples, n_classes) with the
probability of each data example being of a given class.
Return type:
prediction
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.
Parameters:
base_margin (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for base_margin parameter in fit.
base_margin_eval_set (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for base_margin_eval_set parameter in fit.
eval_set (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for eval_set parameter in fit.
feature_weights (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for feature_weights parameter in fit.
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in fit.
sample_weight_eval_set (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight_eval_set parameter in fit.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in fit.
xgb_model (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for xgb_model parameter in fit.
validate_features (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for validate_features parameter in predict_proba.
output_margin (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for output_margin parameter in predict.
validate_features (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for validate_features parameter in predict.
validation_indicator_col (str | None) – For params related to xgboost.XGBRegressor training with
evaluation dataset’s supervision,
set xgboost.spark.SparkXGBRegressor.validation_indicator_col
parameter instead of setting the eval_set parameter in xgboost.XGBRegressor
fit method.
weight_col (str | None) – To specify the weight of the training and validation dataset, set
xgboost.spark.SparkXGBRegressor.weight_col parameter instead of setting
sample_weight and sample_weight_eval_set parameter in xgboost.XGBRegressor
fit method.
base_margin_col (str | None) – To specify the base margins of the training and validation
dataset, set xgboost.spark.SparkXGBRegressor.base_margin_col parameter
instead of setting base_margin and base_margin_eval_set in the
xgboost.XGBRegressor fit method.
num_workers (int) – How many XGBoost workers to be used to train.
Each XGBoost worker corresponds to one spark task.
Device for XGBoost workers, available options are cpu, cuda, and gpu.
force_repartition (bool) – Boolean value to specify if forcing the input dataset to be repartitioned
before XGBoost training.
repartition_random_shuffle (bool) – Boolean value to specify if randomly shuffling the dataset when repartitioning is required.
enable_sparse_data_optim (bool) – Boolean value to specify if enabling sparse data optimization, if True,
Xgboost DMatrix object will be constructed from sparse matrix instead of
dense matrix.
launch_tracker_on_driver (bool) – Boolean value to indicate whether the tracker should be launched on the driver side or
the executor side.
coll_cfg (Config | None) – The collective configuration. See Config
A thread safe iterable which contains one model for each param map. Each
call to next(modelIterator) will return (index, model) where model was fit
using paramMaps[index]. index values may not be sequential.
validation_indicator_col (str | None) – For params related to xgboost.XGBRanker training with
evaluation dataset’s supervision,
set xgboost.spark.SparkXGBRanker.validation_indicator_col
parameter instead of setting the eval_set parameter in xgboost.XGBRanker
fit method.
weight_col (str | None) – To specify the weight of the training and validation dataset, set
xgboost.spark.SparkXGBRanker.weight_col parameter instead of setting
sample_weight and sample_weight_eval_set parameter in xgboost.XGBRanker
fit method.
base_margin_col (str | None) – To specify the base margins of the training and validation
dataset, set xgboost.spark.SparkXGBRanker.base_margin_col parameter
instead of setting base_margin and base_margin_eval_set in the
xgboost.XGBRanker fit method.
Device for XGBoost workers, available options are cpu, cuda, and gpu.
force_repartition (bool) – Boolean value to specify if forcing the input dataset to be repartitioned
before XGBoost training.
repartition_random_shuffle (bool) – Boolean value to specify if randomly shuffling the dataset when repartitioning is required.
enable_sparse_data_optim (bool) – Boolean value to specify if enabling sparse data optimization, if True,
Xgboost DMatrix object will be constructed from sparse matrix instead of
dense matrix.
launch_tracker_on_driver (bool) – Boolean value to indicate whether the tracker should be launched on the driver side or
the executor side.
coll_cfg (Config | None) – The collective configuration. See Config
Note: (..) – The Parameters chart above contains parameters that need special handling.: For a full list of parameters, see entries with Param(parent=… below.
A thread safe iterable which contains one model for each param map. Each
call to next(modelIterator) will return (index, model) where model was fit
using paramMaps[index]. index values may not be sequential.