Sub topic 1
Logging a Trained Model with MLflow
Prerequisites
Assume you can train a scikit-learn model and understand Python dataframes. You also need a Databricks workspace with Unity Catalog enabled and permission to create models in the target schema.
Log a Model with MLflow
MLflow records a trained model and the information needed to use it later. In this example, registered_model_name sends the logged model directly to Unity Catalog.
import mlflow
from mlflow.models import infer_signature
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
mlflow.set_registry_uri("databricks-uc")
X, y = load_iris(return_X_y=True, as_frame=True)
model = RandomForestClassifier(n_estimators=50, random_state=0)
model.fit(X, y)
signature = infer_signature(X, model.predict(X))
with mlflow.start_run():
mlflow.sklearn.log_model(
model,
artifact_path="model",
signature=signature,
input_example=X.head(5),
registered_model_name="main.default.iris_classifier",
)The MLflow run stores the model artifact. The registration step creates a model record and a version in Unity Catalog.
Add a Signature and Input Example
A model signature describes the expected input columns, data types, and output type. Unity Catalog requires a signature for registered models. infer_signature derives one from example inputs and outputs.
An input example is a small sample that shows how to call the model. It also helps users understand the expected dataframe shape. Do not use sensitive production data as the example.
Use the Unity Catalog Namespace
Unity Catalog identifies a model with three names:
| Part | Example | Purpose |
|---|---|---|
| Catalog | `main` | Top-level data governance boundary |
| Schema | `default` | Groups related objects |
| Model | `iris_classifier` | Registered model and its versions |
The full name is catalog.schema.model, such as main.default.iris_classifier. Use this complete name in MLflow, permissions, and serving configuration.
Register and Identify Versions
Each new registration creates another model version. Later chapters use aliases to give a stable name, such as champion, to the version selected for serving. This avoids putting a hard-coded version number in application code.
Exercise
Why should this model include both a signature and an input example?
Show answer
The signature records the model's input and output contract, while the input example demonstrates the expected request shape.