Live Notebook

You can run this notebook in a live session Binder or view it on Github.

Scale XGBoost

Dask and XGBoost can work together to train gradient boosted trees in parallel. This notebook shows how to use Dask and XGBoost together.

XGBoost provides a powerful prediction framework, and it works well in practice. It wins Kaggle contests and is popular in industry because it has good performance and can be easily interpreted (i.e., it’s easy to find the important features from a XGBoost model).

Dask logo Dask logo

Setup Dask

We setup a Dask client, which provides performance and progress metrics via the dashboard.

You can view the dashboard by clicking the link after running the cell.

from dask.distributed import Client

client = Client(n_workers=4, threads_per_worker=1)



Connection method: Cluster object Cluster type: distributed.LocalCluster

Cluster Info

Create data

First we create a bunch of synthetic data, with 100,000 examples and 20 features.

from dask_ml.datasets import make_classification

X, y = make_classification(n_samples=100000, n_features=20,
                           chunks=1000, n_informative=4,
/usr/share/miniconda3/envs/dask-examples/lib/python3.9/site-packages/dask/ UserWarning: Running on a single-machine scheduler when a distributed client is active might lead to unexpected results.
Array Chunk
Bytes 15.26 MiB 156.25 kiB
Shape (100000, 20) (1000, 20)
Count 100 Tasks 100 Chunks
Type float64 numpy.ndarray
20 100000

Dask-XGBoost works with both arrays and dataframes. For more information on creating dask arrays and dataframes from real data, see documentation on Dask arrays or Dask dataframes.

Split data for training and testing

We split our dataset into training and testing data to aid evaluation by making sure we have a fair test:

from dask_ml.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15)

Now, let’s try to do something with this data using dask-xgboost.

Train Dask-XGBoost

import dask
import xgboost
import dask_xgboost
/usr/share/miniconda3/envs/dask-examples/lib/python3.9/site-packages/xgboost/ FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.
  from pandas import MultiIndex, Int64Index

dask-xgboost is a small wrapper around xgboost. Dask sets XGBoost up, gives XGBoost data and lets XGBoost do it’s training in the background using all the workers Dask has available.

Let’s do some training:

params = {'objective': 'binary:logistic',
          'max_depth': 4, 'eta': 0.01, 'subsample': 0.5,
          'min_child_weight': 0.5}

bst = dask_xgboost.train(client, params, X_train, y_train, num_boost_round=10)
Exception in thread Thread-4:
Traceback (most recent call last):
  File "/usr/share/miniconda3/envs/dask-examples/lib/python3.9/", line 973, in _bootstrap_inner
  File "/usr/share/miniconda3/envs/dask-examples/lib/python3.9/", line 910, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/share/miniconda3/envs/dask-examples/lib/python3.9/site-packages/dask_xgboost/", line 365, in join
    while self.thread.isAlive():
AttributeError: 'Thread' object has no attribute 'isAlive'

Visualize results

The bst object is a regular xgboost.Booster object.

<xgboost.core.Booster at 0x7ff9c8b16610>

This means all the methods mentioned in the XGBoost documentation are available. We show two examples to expand on this, but these examples are of XGBoost instead of Dask.

Plot feature importance

%matplotlib inline
import matplotlib.pyplot as plt

ax = xgboost.plot_importance(bst, height=0.8, max_num_features=9)
ax.grid(False, axis="y")
ax.set_title('Estimated feature importance')

We specified that only 4 features were informative while creating our data, and only 3 features show up as important.

Plot the Receiver Operating Characteristic curve

We can use a fancier metric to determine how well our classifier is doing by plotting the Receiver Operating Characteristic (ROC) curve:

y_hat = dask_xgboost.predict(client, bst, X_test).persist()
[19:24:16] WARNING: /home/conda/feedstock_root/build_artifacts/xgboost-split_1645117766796/work/src/ Empty dataset at worker: 0
Array Chunk
Bytes 58.59 kiB 600 B
Shape (15000,) (150,)
Count 100 Tasks 100 Chunks
Type float32 numpy.ndarray
15000 1
from sklearn.metrics import roc_curve

y_test, y_hat = dask.compute(y_test, y_hat)
fpr, tpr, _ = roc_curve(y_test, y_hat)
from sklearn.metrics import auc

fig, ax = plt.subplots(figsize=(5, 5))
ax.plot(fpr, tpr, lw=3,
        label='ROC Curve (area = {:.2f})'.format(auc(fpr, tpr)))
ax.plot([0, 1], [0, 1], 'k--', lw=2)
    xlim=(0, 1),
    ylim=(0, 1),
    title="ROC Curve",
    xlabel="False Positive Rate",
    ylabel="True Positive Rate",

This Receiver Operating Characteristic (ROC) curve tells how well our classifier is doing. We can tell it’s doing well by how far it bends the upper-left. A perfect classifier would be in the upper-left corner, and a random classifier would follow the diagonal line.

The area under this curve is area = 0.76. This tells us the probability that our classifier will predict correctly for a randomly chosen instance.

Learn more