---
title: Deploy a scikit-learn model with Model Serving
description: Train a scikit-learn random forest on the iris dataset, 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-scikit-learn
---

# Deploy a scikit-learn model with Model Serving

This example trains a scikit-learn random forest on the iris dataset, serves it on a CPU Model Serving endpoint, queries it, and deletes it.

The iris dataset comes with scikit-learn, so the example doesn't download the dataset.

For the shortest path, see [Model Serving quickstart](https://docs.databricks.com/gcp/en/machine-learning/model-serving/model-serving-quickstart.md).

For the same steps with an XGBoost model, see [Score an XGBoost model with Model Serving](https://docs.databricks.com/gcp/en/machine-learning/model-serving/model-serving-example-xgboost.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).
* The Unity Catalog privileges to register and delete models, 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.

#### Deploy a scikit-learn model notebook

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

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

The sample runs on serverless compute. 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
dbutils.library.restartPython()
```

The cell prints a pip summary, then a line about restarting the kernel. The last line restarts Python. Run the rest of the cells in order, in the same notebook, because each step uses names that an earlier step defines. The log cell uses the `name` argument of `log_model`, which MLflow 2.22.0 doesn't have, so this cell installs MLflow 3.

### <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`. Replace `<catalog>` and `<schema>` with a catalog and schema where you have the privileges described under [Requirements](https://docs.databricks.com/gcp/en/machine-learning/model-serving/model-serving-example-scikit-learn.md#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_random_forest"
ENDPOINT_NAME = "iris-random-forest"
FULL_MODEL_NAME = f"{CATALOG}.{SCHEMA}.{MODEL}"
```

The cell shows no output. 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-train-the-model" />Load the data and train the model

To load the data and train the model, run the following:

```python
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
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
)
model = RandomForestClassifier(n_estimators=100, random_state=0).fit(X_train, y_train)
```

The sample passes `as_frame=True`. The dataset has 150 instances, 50 in each of three classes, and four numeric attributes. The cell shows no output.

### <a id="log-and-register-the-model" />Log and register the model

To log the model and register it, run the following:

```python
import mlflow.sklearn
from mlflow.models import infer_signature

signature = infer_signature(X_train, model.predict(X_train))
info = mlflow.sklearn.log_model(
    sk_model=model,
    name="model",
    signature=signature,
    input_example=X_train.head(2),
    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_random_forest
Version: 1
```

The call also prints lines that link to the logged model and to the new model version. MLflow also writes two warnings that say no run link is recorded for the model version, and the cell still finishes.

Unity Catalog requires a signature on each new model version, so `infer_signature` builds one from the 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 creates the registered model if none exists.

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

The endpoint serves the version that the log cell registered, as a CPU workload of size Small. For the sizes and the other 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)
```

To see the endpoint's state, read `state.ready` and `state.config_update` in the output below. After a successful create, `state.ready` shows `READY` and `state.config_update` shows `NOT_UPDATING`. `state.ready` is `READY` only when every served entity in the active config is ready. The cell prints enum names such as `EndpointStateReady.READY` rather than the bare words `READY` and `NOT_UPDATING`.

`create_and_wait` returns when `state.config_update` is `NOT_UPDATING`, and it doesn't check `state.ready`. It raises an error when `config_update` becomes `UPDATE_FAILED` or `UPDATE_CANCELED`, and it raises `TimeoutError` at its deadline. The timeout is client-side only, and the endpoint keeps deploying after the call times out.

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

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

The request sends two rows from the test split, and `columns` names the four feature columns. To query the endpoint, 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_random_forest-1'}
```

The log cell logged a signature, so model inputs are checked at inference, and an error is reported if they don't match it. MLflow's signature check fails when a required input field is missing, and it ignores extra fields.

A query can get a 404 for a short time after `state.ready` shows `READY`, so the sample retries. The SDK raises `NotFound` for that 404. The loop makes up to 12 tries, and it waits 10 seconds after each 404.

The `predictions` list has one value for each row in the request. The `served-model-name` field holds the name of the served entity that answered. The sample doesn't set `name`, so the default name is the last part of the three-level model name, a hyphen, and the version, here `iris_random_forest-1`. A new version changes the default name too.

### <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 either delete. The endpoint delete runs first. 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_random_forest
```

## Additional resources

* [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)
