Sub topic 1
Logging a Trained Model with MLflow
A model that exists only as a Python object in a notebook cannot be shared, versioned, or served. MLflow solves this by saving the model, plus the information needed to load it again, as a tracked artifact. This chapter shows how to log a scikit-learn model. Later chapters register that logged model in Unity Catalog and serve it.
Prerequisites
This chapter assumes you have:
- Basic Python and a scikit-learn style train/predict workflow.
- Access to a Databricks workspace and a notebook attached to compute.
- A rough idea of what a REST API and a JSON request are. You need this later in the tutorial, not for this chapter.
- General awareness of catalogs, schemas and tables in Unity Catalog.
MLflow is preinstalled on Databricks Runtime for Machine Learning. On other runtimes, run %pip install mlflow scikit-learn first.
What logging produces
MLflow organizes work into runs. A run is one execution of your training code, and it records parameters, metrics and artifacts (files). Logging a model attaches a folder of files to the active run.
That folder contains the serialized model, an MLmodel file describing how to load it, and environment files such as requirements.txt and conda.yaml. The MLmodel file lists one or more flavors. A flavor is a standard way to load the model. A scikit-learn model gets the sklearn flavor and the generic python_function (pyfunc) flavor.
Logging a model
The example trains a small classifier, logs it inside a run, and loads it back.
import mlflow
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
X, y = load_iris(return_X_y=True, as_frame=True)
model = RandomForestClassifier(n_estimators=50, random_state=0).fit(X, y)
with mlflow.start_run() as run:
mlflow.log_param("n_estimators", 50)
mlflow.sklearn.log_model(model, artifact_path="model")
run_id = run.info.run_id
loaded = mlflow.pyfunc.load_model(f"runs:/{run_id}/model")
print(loaded.predict(X.head(3)))Here is what each part does:
mlflow.start_run()opens a run. Everything logged inside thewithblock belongs to it.mlflow.log_paramrecords a hyperparameter so you can compare runs later.mlflow.sklearn.log_modelsaves the model under the artifact pathmodel. Use the log function that matches your library, such asmlflow.sklearn,mlflow.xgboostormlflow.pytorch.runs:/<run_id>/modelis a model URI. It points to the artifact path inside a specific run.
Loading with mlflow.pyfunc.load_model returns a generic wrapper with a single predict method. This is the same interface that Model Serving uses, so testing it now catches problems early.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `log_model` fails with a missing run or experiment error | Code runs outside a notebook with no tracking target | Call `mlflow.set_tracking_uri("databricks")` and authenticate, or run in a notebook |
| Loading fails with a missing module error | The loading environment differs from the training one | Install the packages listed in the logged `requirements.txt` |
| Model URI not found | Wrong run ID or artifact path | Copy the run ID from the run page and match the `artifact_path` you used |
| Predictions differ from the original model | Input columns are in a different order or have different types | Pass a DataFrame with the training column names and types |
The last row matters most for serving. At this point the model does not record what inputs it expects. The next chapter adds a signature, which stores the expected column names and types with the model.
Checking your work
Open the run in the Experiments page of the workspace. The Artifacts tab should show the model folder with an MLmodel file. Open that file and find the flavors section to confirm both sklearn and python_function appear.
Exercise
You logged a model with artifact_path="model" and the run ID is abc123. What model URI do you pass to mlflow.pyfunc.load_model to load it, and why does loading through pyfunc matter for serving?
Show answer
The URI is runs:/abc123/model. Pyfunc is the generic flavor with a single predict method, and Model Serving uses the same interface, so a successful pyfunc load and predict is a good early test that the model will work when served.