# Python Package Introduction

This document gives a basic walkthrough of the xgboost package for Python.  The Python
package is consisted of 3 different interfaces, including native interface, scikit-learn
interface and dask interface.  For introduction to dask interface please see
[Distributed XGBoost with Dask](../tutorials/dask.html.md).

**List of other Helpful Links**

* [XGBoost Python Feature Walkthrough](examples/index.html.md)
* [Python API Reference](python_api.html.md)

**Contents**

> * [Install XGBoost](#install-xgboost)
> * [Data Interface](#data-interface)
> * [Setting Parameters](#setting-parameters)
> * [Training](#training)
> * [Early Stopping](#early-stopping)
> * [Prediction](#prediction)
> * [Plotting](#plotting)
> * [Scikit-Learn interface](#scikit-learn-interface)

## Install XGBoost

To install XGBoost, follow instructions in [Installation Guide](../install.html.md).

To verify your installation, run the following in Python:

```python
import xgboost as xgb
```

<a id="python-data-interface"></a>

## Data Interface

The XGBoost Python module is able to load data from many different types of data format including both CPU and GPU data structures. For a comprehensive list of supported data types, please reference the [Supported Python data structures](data_input.html.md). For a detailed description of text input formats, please visit [Text Input Format of DMatrix](../tutorials/input_format.html.md).

The input data is stored in a [`DMatrix`](python_api.html.md#xgboost.DMatrix) object. For the sklearn estimator interface, a `DMatrix` or a `QuantileDMatrix` is created depending on the chosen algorithm and the input, see the sklearn API reference for details. We will illustrate some of the basic input types using the `DMatrix` here.

* To load a NumPy array into [`DMatrix`](python_api.html.md#xgboost.DMatrix):
  ```python
  data = np.random.rand(5, 10)  # 5 entities, each contains 10 features
  label = np.random.randint(2, size=5)  # binary target
  dtrain = xgb.DMatrix(data, label=label)
  ```
* To load a [`scipy.sparse`](https://docs.scipy.org/doc/scipy/reference/sparse.html#module-scipy.sparse) array into [`DMatrix`](python_api.html.md#xgboost.DMatrix):
  ```python
  csr = scipy.sparse.csr_matrix((dat, (row, col)))
  dtrain = xgb.DMatrix(csr)
  ```
* To load a Pandas data frame into [`DMatrix`](python_api.html.md#xgboost.DMatrix):
  ```python
  data = pandas.DataFrame(np.arange(12).reshape((4,3)), columns=['a', 'b', 'c'])
  label = pandas.DataFrame(np.random.randint(2, size=4))
  dtrain = xgb.DMatrix(data, label=label)
  ```
* Saving [`DMatrix`](python_api.html.md#xgboost.DMatrix) into a XGBoost binary file:
  ```python
  data = np.random.rand(5, 10)  # 5 entities, each contains 10 features
  label = np.random.randint(2, size=5)  # binary target
  dtrain.save_binary('train.buffer')
  ```
* Missing values can be replaced by a default value in the [`DMatrix`](python_api.html.md#xgboost.DMatrix) constructor:
  ```python
  dtrain = xgb.DMatrix(data, label=label, missing=np.NaN)
  ```
* Weights can be set when needed:
  ```python
  w = np.random.rand(5, 1)
  dtrain = xgb.DMatrix(data, label=label, missing=np.NaN, weight=w)
  ```

## Setting Parameters

XGBoost can use either a list of pairs or a dictionary to set [parameters](../parameter.html.md). For instance:

* Booster parameters
  ```python
  param = {'max_depth': 2, 'eta': 1, 'objective': 'binary:logistic'}
  param['nthread'] = 4
  param['eval_metric'] = 'auc'
  ```
* You can also specify multiple eval metrics:
  ```python
  param['eval_metric'] = ['auc', 'ams@0']

  # alternatively:
  # plst = param.items()
  # plst += [('eval_metric', 'ams@0')]
  ```
* Specify validations set to watch performance
  ```python
  evallist = [(dtrain, 'train'), (dtest, 'eval')]
  ```

## Training

Training a model requires a parameter list and data set.

```python
num_round = 10
bst = xgb.train(param, dtrain, num_round, evallist)
```

After training, the model can be saved into `JSON` or `UBJSON`:

```python
bst.save_model('model.ubj')
```

The model and its feature map can also be dumped to a text file.

```python
# dump model
bst.dump_model('dump.raw.txt')
# dump model with feature map
bst.dump_model('dump.raw.txt', 'featmap.txt')
```

A saved model can be loaded as follows:

```python
bst = xgb.Booster({'nthread': 4})  # init model
bst.load_model('model.ubj')  # load model data
```

Methods including update and boost from [`xgboost.Booster`](python_api.html.md#xgboost.Booster) are designed for
internal usage only.  The wrapper function [`xgboost.train`](python_api.html.md#xgboost.train) does some
pre-configuration including setting up caches and some other parameters.

## Early Stopping

If you have a validation set, you can use early stopping to find the optimal number of boosting rounds.
Early stopping requires at least one set in `evals`. If there’s more than one, it will use the last.

```python
train(..., evals=evals, early_stopping_rounds=10)
```

The model will train until the validation score stops improving. Validation error needs to decrease at least every `early_stopping_rounds` to continue training.

If early stopping occurs, the model will have two additional fields: `bst.best_score`, `bst.best_iteration`.  Note that [`xgboost.train()`](python_api.html.md#xgboost.train) will return a model from the last iteration, not the best one.

This works with both metrics to minimize (RMSE, log loss, etc.) and to maximize (MAP, NDCG, AUC). Note that if you specify more than one evaluation metric the last one in `param['eval_metric']` is used for early stopping.

## Prediction

A model that has been trained or loaded can perform predictions on data sets.

```python
# 7 entities, each contains 10 features
data = np.random.rand(7, 10)
dtest = xgb.DMatrix(data)
ypred = bst.predict(dtest)
```

If early stopping is enabled during training, you can get predictions from the best iteration with `bst.best_iteration`:

```python
ypred = bst.predict(dtest, iteration_range=(0, bst.best_iteration + 1))
```

## Plotting

You can use plotting module to plot importance and output tree.

To plot importance, use [`xgboost.plot_importance()`](python_api.html.md#xgboost.plot_importance). This function requires `matplotlib` to be installed.

```python
xgb.plot_importance(bst)
```

To plot the output tree via `matplotlib`, use [`xgboost.plot_tree()`](python_api.html.md#xgboost.plot_tree), specifying the ordinal number of the target tree. This function requires `graphviz` and `matplotlib`.

```python
xgb.plot_tree(bst, num_trees=2)
```

When you use `IPython`, you can use the [`xgboost.to_graphviz()`](python_api.html.md#xgboost.to_graphviz) function, which converts the target tree to a `graphviz` instance. The `graphviz` instance is automatically rendered in `IPython`.

```python
xgb.to_graphviz(bst, num_trees=2)
```

## Scikit-Learn interface

XGBoost provides an easy to use scikit-learn interface for some pre-defined models
including regression, classification and ranking. See [Using the Scikit-Learn Estimator Interface](sklearn_estimator.html.md)
for more info.

```python
# Use "hist" for training the model.
reg = xgb.XGBRegressor(tree_method="hist", device="cuda")
# Fit the model using predictor X and response y.
reg.fit(X, y)
# Save model into JSON format.
reg.save_model("regressor.json")
```

User can still access the underlying booster model when needed:

```python
booster: xgb.Booster = reg.get_booster()
```
