Real-time fraud scoring with Model Serving
This example trains a scikit-learn classifier on synthetic transactions, registers it in Unity Catalog, serves it on a CPU Model Serving endpoint, and scores one transaction.
The transactions are generated in the notebook, so the example downloads no data.
Requirements
- A workspace in a supported region.
- The Unity Catalog privileges to register and delete models, described in Manage model lifecycle in Unity Catalog.
Run the example
To run every step, import the notebook. Run the cells in order, in the same notebook.
Real-time fraud scoring notebook
Install the packages
To install the packages, run the following:
%pip install -U "mlflow>=3" "databricks-sdk>=0.102.0" scikit-learn==1.9.1 pandas==3.1.1
dbutils.library.restartPython()
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. To set the names, run the following:
# Set these once. Replace the placeholders with your own names.
CATALOG = "<catalog>"
SCHEMA = "<schema>"
MODEL = "fraud_scoring_model"
ENDPOINT_NAME = "fraud-scoring"
FULL_MODEL_NAME = f"{CATALOG}.{SCHEMA}.{MODEL}"
The endpoint name must be unique across the workspace.
Generate the transactions and train the model
The cell builds 20,000 synthetic transactions, each with an amount, an hour from 0 to 23, and a merchant_risk score from 0 to 1. It gives each transaction a fraud probability that goes up for larger amounts, for hours before 6 AM, and for riskier merchants. It then draws a fraud label from that probability and trains a classifier on the labeled rows. Run the following:
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier
# Synthetic transactions. The fixed seed makes every run build the same data.
rng = np.random.default_rng(42)
n = 20_000
X = pd.DataFrame(
{
"amount": rng.lognormal(mean=3.5, sigma=1.0, size=n),
"hour": rng.integers(0, 24, size=n),
"merchant_risk": rng.uniform(0, 1, size=n),
}
)
# Larger amounts, late-night hours, and risky merchants raise the fraud odds.
logit = (
-3.5
+ 0.5 * (np.log(X["amount"]) - 3.5)
+ 1.2 * (X["hour"] < 6)
+ 2.0 * (X["merchant_risk"] - 0.5)
)
y = (rng.uniform(size=n) < 1 / (1 + np.exp(-logit))).astype(int)
print("Fraud rate in the training data:", round(y.mean(), 4))
model = HistGradientBoostingClassifier(random_state=0).fit(X, y)
print("Classes:", model.classes_)
The cell prints the following:
Fraud rate in the training data: 0.056
Classes: [0 1]
Label 1 is fraud in this example, so column 1 of predict_proba is the fraud probability.
Log and register the model
To log the model and register it, run the following:
import mlflow.sklearn
from mlflow.models import infer_signature
signature = infer_signature(X, model.predict_proba(X))
info = mlflow.sklearn.log_model(
sk_model=model,
name="model",
signature=signature,
input_example=X.head(2),
pyfunc_predict_fn="predict_proba",
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:
Registered model: <catalog>.<schema>.fraud_scoring_model
Version: 1
Unity Catalog requires a signature on each new model version. infer_signature builds the signature from the training data and the model's predictions.
This example sets pyfunc_predict_fn to predict_proba, which returns the class probabilities of the input samples, one column for each class.
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.
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. To create the endpoint and wait for it, run the following:
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:
state.ready: EndpointStateReady.READY
state.config_update: EndpointStateConfigUpdate.NOT_UPDATING
The scale_to_zero_enabled=True argument lets the endpoint scale to zero.
For cold starts on an endpoint that scales to zero, see Fix slow requests on Model Serving endpoints.
Query the endpoint
To score one transaction, run the following:
import time
from databricks.sdk.errors import NotFound
from databricks.sdk.service.serving import DataframeSplitInput
FEATURE_COLUMNS = ["amount", "hour", "merchant_risk"]
transaction = [980.0, 3, 0.9]
# The endpoint can return 404 for a short time after it reports READY, so retry.
for attempt in range(12):
try:
response = w.serving_endpoints.query(
name=ENDPOINT_NAME,
dataframe_split=DataframeSplitInput(columns=FEATURE_COLUMNS, data=[transaction]),
)
break
except NotFound:
time.sleep(10)
else:
raise TimeoutError("The endpoint didn't accept the request after 12 tries.")
print("predictions:", response.predictions)
print("Fraud probability:", round(response.predictions[0][1], 4))
The cell prints the following:
predictions: [[0.4326279464893209, 0.5673720535106791]]
Fraud probability: 0.5674
The install cell pins scikit-learn 1.9.1, because other scikit-learn versions can train a different model from the same data and print different probabilities.
The request sends one row with three columns, amount, hour, and merchant_risk. In this sample, hour is a whole number from 0 to 23, and merchant_risk runs from 0 to 1.
For the request body when you call the endpoint over REST, see Format scoring requests.
The response has a predictions key with one entry per input row. Each entry has two values, one for each class.
A query can get a 404 for a short time after state.ready shows READY, so the sample retries for up to 12 tries.
To score a transaction from the Serving UI, open the endpoint, select Query endpoint, and insert JSON. If the model has a logged input example, select Show Example to load it.
This example doesn't measure how fast the endpoint answers. A load test measures how the endpoint performs under different traffic levels, so you can size it. See Size and load test custom model serving endpoints.
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:
w.serving_endpoints.delete(name=ENDPOINT_NAME)
print("Deleted endpoint:", ENDPOINT_NAME)
The cell prints the following:
Deleted endpoint: fraud-scoring
To delete the model version and the registered model, run the following:
from mlflow import MlflowClient
client = MlflowClient()
client.delete_model_version(name=FULL_MODEL_NAME, version=MODEL_VERSION)
client.delete_registered_model(name=FULL_MODEL_NAME)
print("Deleted model:", FULL_MODEL_NAME)
The cell prints the following:
Deleted model: <catalog>.<schema>.fraud_scoring_model