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).

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.

In [1]:
from dask.distributed import Client

client = Client(n_workers=4, threads_per_worker=1)
client
Out[1]:

Client

Cluster

  • Workers: 4
  • Cores: 4
  • Memory: 15.69 GB

Create data

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

In [2]:
from dask_ml.datasets import make_classification

X, y = make_classification(n_samples=100000, n_features=20,
                           chunks=1000, n_informative=4,
                           random_state=0)
X
Out[2]:
dask.array<normal, shape=(100000, 20), dtype=float64, chunksize=(1000, 20)>

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:

In [3]:
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

In [4]:
import dask_xgboost
import xgboost

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:

In [5]:
%%time
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)
CPU times: user 3.04 s, sys: 168 ms, total: 3.21 s
Wall time: 12.7 s

Visualize results

The bst object is a regular xgboost.Booster object.

In [6]:
bst
Out[6]:
<xgboost.core.Booster at 0x7fbf8d122400>

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

In [7]:
%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')
plt.show()
../_images/machine-learning_xgboost_20_0.png

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:

In [8]:
y_hat = dask_xgboost.predict(client, bst, X_test).persist()
y_hat
Out[8]:
dask.array<_predict_part, shape=(15000,), dtype=float32, chunksize=(150,)>
In [9]:
from sklearn.metrics import roc_curve

fpr, tpr, _ = roc_curve(y_test, y_hat)
In [10]:
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)
ax.set(
    xlim=(0, 1),
    ylim=(0, 1),
    title="ROC Curve",
    xlabel="False Positive Rate",
    ylabel="True Positive Rate",
)
ax.legend();
plt.show()
../_images/machine-learning_xgboost_25_0.png

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 horizontal 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