---
title: Score an XGBoost model with Model Serving
description: Train an XGBoost classifier on the iris dataset, log it with mlflow\.xgboost, serve it on a CPU Model Serving endpoint, query it, and delete it.
canonical_url: https://docs.databricks.com/gcp/en/machine-learning/model-serving/model-serving-example-xgboost
---

# Score an XGBoost model with Model Serving

This example trains an XGBoost classifier on the iris dataset and logs it with `mlflow.xgboost`. It then serves the model on a CPU Model Serving endpoint, queries the endpoint, and deletes the endpoint and the model.

The iris dataset comes with scikit-learn, so the example downloads no data.

If you prefer a scikit-learn model, see [Deploy a scikit-learn model with Model Serving](https://docs.databricks.com/gcp/en/machine-learning/model-serving/model-serving-example-scikit-learn.md).

## <a id="requirements" />Requirements

* A workspace in a [supported region](https://docs.databricks.com/gcp/en/machine-learning/model-serving/model-serving-limits.md#regions).
* Unity Catalog permissions for models, as described in [Manage model lifecycle in Unity Catalog](https://docs.databricks.com/gcp/en/machine-learning/manage-model-lifecycle/index.md).

## <a id="run-the-example" />Run the example

To run every step, import the notebook. Run the cells in order, in the same notebook.

#### Score an XGBoost model notebook

[Get notebook](https://docs.databricks.com/notebooks/source/machine-learning/example-xgboost.html)

### <a id="install-the-packages" />Install the packages

To install the packages, run the following:

```python
%pip install -U "mlflow>=3" "databricks-sdk>=0.102.0" scikit-learn==1.9.1 pandas==3.1.1 xgboost==3.4.1
dbutils.library.restartPython()
```

The install can print a pip warning that `databricks-connect` requires pandas below 3. The install still finishes, and the sample runs.

The output ends with a message about restarting the kernel.

### <a id="set-the-model-and-endpoint-names" />Set the model and endpoint names

A Unity Catalog model name has three levels, `catalog.schema.model`, and the MLflow APIs take that name. Replace `<catalog>` and `<schema>` with a catalog and schema where you have the permissions listed under Requirements.

To set the names, run the following:

```python
# Set these once. Replace the placeholders with your own names.
CATALOG = "<catalog>"
SCHEMA = "<schema>"
MODEL = "iris_xgboost"
ENDPOINT_NAME = "iris-xgboost"
FULL_MODEL_NAME = f"{CATALOG}.{SCHEMA}.{MODEL}"
```

The endpoint name must be unique across the workspace. If the name is taken, change `ENDPOINT_NAME` in the cell above.

### <a id="load-the-data-and-split-it" />Load the data and split it

To load the iris data and split it, run the following:

```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

iris = load_iris(as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
    iris.data, iris.target, test_size=0.2, random_state=0
)
```

The `as_frame=True` argument makes the data a pandas DataFrame. The dataset has 150 rows, 50 in each of three classes, and four numeric features.

### <a id="train-and-log-the-model" />Train and log the model

To train the XGBoost classifier and log it, run the following:

```python
import mlflow.xgboost
from mlflow.models import infer_signature
from xgboost import XGBClassifier

xgb_model = XGBClassifier().fit(X_train, y_train)
signature = infer_signature(X_train, xgb_model.predict(X_train))
info = mlflow.xgboost.log_model(
    xgb_model=xgb_model,
    name="model",
    signature=signature,
    registered_model_name=FULL_MODEL_NAME,
)
MODEL_VERSION = str(info.registered_model_version)
print("Registered model:", FULL_MODEL_NAME)
print("Version:", MODEL_VERSION)
```

The cell prints the following:

```text
Registered model: <catalog>.<schema>.iris_xgboost
Version: 1
```

Unity Catalog requires a [signature](https://docs.databricks.com/gcp/en/machine-learning/model-serving/custom-models.md#signature-and-input-examples) on each new model version. The cell builds the signature with `infer_signature` from the training inputs and the model's predictions on them.

When `registered_model_name` is set, `log_model` creates a model version under that name, and it also creates the registered model if none exists.

The `entity_version` field of `ServedEntityInput` is an optional string, and the cell converts the version with `str()`.

This example doesn't pass `pip_requirements`, so `log_model` infers the requirements from the current software environment. For how the endpoint's container uses them, see [Deployment container and dependencies](https://docs.databricks.com/gcp/en/machine-learning/model-serving/custom-models.md#deployment-container-and-dependencies).

The cell also writes two MLflow warnings that say no run link is recorded for the model version, and it still finishes.

### <a id="create-the-endpoint" />Create the endpoint

The endpoint serves the version that the log cell registered, as a CPU workload. For the workload sizes and the other endpoint settings, see [Create an endpoint for custom models in Model Serving](https://docs.databricks.com/gcp/en/machine-learning/model-serving/create-manage-serving-endpoints.md). To create the endpoint and wait for it, run the following:

```python
from databricks.sdk import WorkspaceClient
from databricks.sdk.service.serving import EndpointCoreConfigInput, ServedEntityInput, ServingModelWorkloadType

w = WorkspaceClient()
endpoint = w.serving_endpoints.create_and_wait(
    name=ENDPOINT_NAME,
    config=EndpointCoreConfigInput(
        name=ENDPOINT_NAME,
        served_entities=[
            ServedEntityInput(
                entity_name=FULL_MODEL_NAME,
                entity_version=MODEL_VERSION,
                workload_type=ServingModelWorkloadType.CPU,
                workload_size="Small",
                scale_to_zero_enabled=True,
            )
        ],
    ),
)
print("state.ready:", endpoint.state.ready)
print("state.config_update:", endpoint.state.config_update)
```

The cell prints the following:

```text
state.ready: EndpointStateReady.READY
state.config_update: EndpointStateConfigUpdate.NOT_UPDATING
```

The `scale_to_zero_enabled=True` argument lets the endpoint scale to zero.

### <a id="query-the-endpoint" />Query the endpoint

To query the endpoint with the first two rows of the test set, run the following:

```python
import time
from databricks.sdk.errors import NotFound
from databricks.sdk.service.serving import DataframeSplitInput

FEATURE_COLUMNS = ["sepal length (cm)", "sepal width (cm)", "petal length (cm)", "petal width (cm)"]
rows = X_test[FEATURE_COLUMNS].head(2).values.tolist()

# Retry while the endpoint is not accepting requests yet.
for attempt in range(12):
    try:
        response = w.serving_endpoints.query(
            name=ENDPOINT_NAME,
            dataframe_split=DataframeSplitInput(columns=FEATURE_COLUMNS, data=rows),
        )
        break
    except NotFound:
        time.sleep(10)
else:
    raise TimeoutError("The endpoint didn't accept the request after 12 tries.")
QUERY_TRIES = attempt + 1
print(response.as_dict())
```

The cell prints the following:

```text
{'predictions': [2, 1], 'served-model-name': 'iris_xgboost-1'}
```

The request names the four feature columns, and the logged signature checks the inputs against them.

For the request body when you call the endpoint over REST, see [Format scoring requests](https://docs.databricks.com/gcp/en/machine-learning/model-serving/score-custom-model-endpoints.md#formats).

A query can get a 404 for a short time after `state.ready` shows `READY`, so the sample retries for up to 12 tries.

The `predictions` list has one value for each row in the request. The `served-model-name` value is the name of the [served entity](https://docs.databricks.com/gcp/en/machine-learning/model-serving/glossary.md#served-entity) that answered. For this model, the default name is the last part of the three-level model name, a hyphen, and the version, so it reads `iris_xgboost-1`.

The model was fit on the iris `target` codes. To turn the predictions into class names, index `iris.target_names` with them, as the [load\_iris example in the scikit-learn reference](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) does.

### <a id="delete-the-endpoint-and-the-registered-model" />Delete the endpoint and the registered model

Optionally, delete the endpoint and the registered model. You can't undo deleting the endpoint or the registered model. To delete the endpoint, run the following:

```python
delete_result = w.serving_endpoints.delete(name=ENDPOINT_NAME)
print("delete returned:", repr(delete_result))
```

The cell prints the following:

```text
delete returned: None
```

To delete the registered model with the MLflow client, run the following:

```python
from mlflow import MlflowClient

MlflowClient().delete_registered_model(name=FULL_MODEL_NAME)
print("Deleted registered model:", FULL_MODEL_NAME)
```

The cell prints the following:

```text
Deleted registered model: <catalog>.<schema>.iris_xgboost
```

## Additional resources

* [Deploy custom models with Model Serving](https://docs.databricks.com/gcp/en/machine-learning/model-serving/custom-models.md)
* [Create an endpoint for custom models in Model Serving](https://docs.databricks.com/gcp/en/machine-learning/model-serving/create-manage-serving-endpoints.md)
* [Query serving endpoints for custom models](https://docs.databricks.com/gcp/en/machine-learning/model-serving/score-custom-model-endpoints.md)
* [Manage endpoints for Model Serving](https://docs.databricks.com/gcp/en/machine-learning/model-serving/manage-serving-endpoints.md)
* [mlflow.xgboost](https://mlflow.org/docs/latest/api_reference/python_api/mlflow.xgboost.html)
