{
"cells": [
{
"cell_type": "markdown",
"id": "5fb89b3d",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"# Training a model with distributed XGBoost\n",
"In this example we will train a model in Ray AIR using distributed XGBoost."
]
},
{
"cell_type": "markdown",
"id": "53d57c1f",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"Let's start with installing our dependencies:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "41f20cc1",
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"!pip install -qU \"ray[tune]\" xgboost_ray"
]
},
{
"cell_type": "markdown",
"id": "d2fe8d4a",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"Then we need some imports:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "7232303d",
"metadata": {},
"outputs": [],
"source": [
"import argparse\n",
"from typing import Tuple\n",
"\n",
"import pandas as pd\n",
"\n",
"import ray\n",
"from ray.train.batch_predictor import BatchPredictor\n",
"from ray.train.xgboost import XGBoostPredictor\n",
"from ray.train.xgboost import XGBoostTrainer\n",
"from ray.data.dataset import Dataset\n",
"from ray.air.result import Result\n",
"from ray.data.preprocessors import StandardScaler\n",
"from sklearn.datasets import load_breast_cancer\n",
"from sklearn.model_selection import train_test_split"
]
},
{
"cell_type": "markdown",
"id": "1c75b5ca",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"Next we define a function to load our train, validation, and test datasets."
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "37c4f38f",
"metadata": {},
"outputs": [],
"source": [
"def prepare_data() -> Tuple[Dataset, Dataset, Dataset]:\n",
" data_raw = load_breast_cancer()\n",
" dataset_df = pd.DataFrame(data_raw[\"data\"], columns=data_raw[\"feature_names\"])\n",
" dataset_df[\"target\"] = data_raw[\"target\"]\n",
" train_df, test_df = train_test_split(dataset_df, test_size=0.3)\n",
" train_dataset = ray.data.from_pandas(train_df)\n",
" valid_dataset = ray.data.from_pandas(test_df)\n",
" test_dataset = ray.data.from_pandas(test_df.drop(\"target\", axis=1))\n",
" return train_dataset, valid_dataset, test_dataset"
]
},
{
"cell_type": "markdown",
"id": "9b2850dd",
"metadata": {
"pycharm": {
"name": "#%% md\n"
}
},
"source": [
"The following function will create a XGBoost trainer, train it, and return the result."
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "dae8998d",
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"def train_xgboost(num_workers: int, use_gpu: bool = False) -> Result:\n",
" train_dataset, valid_dataset, _ = prepare_data()\n",
"\n",
" # Scale some random columns\n",
" columns_to_scale = [\"mean radius\", \"mean texture\"]\n",
" preprocessor = StandardScaler(columns=columns_to_scale)\n",
"\n",
" # XGBoost specific params\n",
" params = {\n",
" \"tree_method\": \"approx\",\n",
" \"objective\": \"binary:logistic\",\n",
" \"eval_metric\": [\"logloss\", \"error\"],\n",
" }\n",
"\n",
" trainer = XGBoostTrainer(\n",
" scaling_config={\n",
" \"num_workers\": num_workers,\n",
" \"use_gpu\": use_gpu,\n",
" },\n",
" label_column=\"target\",\n",
" params=params,\n",
" datasets={\"train\": train_dataset, \"valid\": valid_dataset},\n",
" preprocessor=preprocessor,\n",
" num_boost_round=100,\n",
" )\n",
" result = trainer.fit()\n",
" print(result.metrics)\n",
"\n",
" return result"
]
},
{
"cell_type": "markdown",
"id": "ce05af87",
"metadata": {},
"source": [
"Once we have the result, we can do batch inference on the obtained model. Let's define a utility function for this."
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "5b8076d3",
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"def predict_xgboost(result: Result):\n",
" _, _, test_dataset = prepare_data()\n",
"\n",
" batch_predictor = BatchPredictor.from_checkpoint(\n",
" result.checkpoint, XGBoostPredictor\n",
" )\n",
"\n",
" predicted_labels = (\n",
" batch_predictor.predict(test_dataset)\n",
" .map_batches(lambda df: (df > 0.5).astype(int), batch_format=\"pandas\")\n",
" .to_pandas(limit=float(\"inf\"))\n",
" )\n",
" print(f\"PREDICTED LABELS\\n{predicted_labels}\")\n",
"\n",
" shap_values = batch_predictor.predict(test_dataset, pred_contribs=True).to_pandas(\n",
" limit=float(\"inf\")\n",
" )\n",
" print(f\"SHAP VALUES\\n{shap_values}\")\n"
]
},
{
"cell_type": "markdown",
"id": "7e172f66",
"metadata": {},
"source": [
"Now we can run the training:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "0f96d62b",
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"2022-05-19 11:44:42,413\tINFO services.py:1483 -- View the Ray dashboard at \u001B[1m\u001B[32mhttp://127.0.0.1:8265\u001B[39m\u001B[22m\n"
]
},
{
"data": {
"text/html": [
"== Status ==
Current time: 2022-05-19 11:45:00 (running for 00:00:13.93)
Memory usage on this node: 10.3/16.0 GiB
Using FIFO scheduling algorithm.
Resources requested: 0/16 CPUs, 0/0 GPUs, 0.0/4.5 GiB heap, 0.0/2.0 GiB objects
Result logdir: /Users/kai/ray_results/XGBoostTrainer_2022-05-19_11-44-45
Number of trials: 1/1 (1 TERMINATED)
Trial name | status | loc | iter | total time (s) | train-logloss | train-error | valid-logloss |
---|---|---|---|---|---|---|---|
XGBoostTrainer_b273b_00000 | TERMINATED | 127.0.0.1:11036 | 100 | 9.03935 | 0.005949 | 0 | 0.07483 |