Sub topic 1
Logging a Trained Model with MLflow
This chapter covers the first step in the path from training to serving: logging a trained model with MLflow. By the end, you will know what a logged model contains, how to log one, and how to load it back and check that it works.
Prerequisites
This chapter assumes the following:
- You can write basic Python and know the scikit-learn train/predict workflow (
fit,predict). - You can run a notebook in a Databricks workspace, or you have MLflow installed locally.
- You know that a REST API accepts JSON requests. You will not call one in this chapter.
- You know roughly what catalogs, schemas and tables are in Unity Catalog. Registering models comes in a later chapter.
What MLflow logging does
MLflow is an open source library for tracking machine learning work. It is built into Databricks. Two of its ideas matter here:
- A run is one execution of your training code. A run records parameters, metrics and files.
- An artifact is a file stored with a run, such as a plot or a serialized model.
Logging a model means saving the trained model as an artifact of a run, in a standard layout that MLflow knows how to load later. Model Serving and the Unity Catalog registry both depend on this layout. A model that only exists in a notebook's memory, or in a pickle file you saved by hand, cannot be registered or served.
A logged model is a directory, not a single file. It usually contains:
| File | Purpose |
|---|---|
| `MLmodel` | A YAML file describing the model: its flavors, signature, and the MLflow version that saved it. |
| `model.pkl` (or similar) | The serialized model in its native format. The file name depends on the flavor. |
| `conda.yaml` | The Conda environment needed to run the model. |
| `python_env.yaml` | The Python version and pip requirements. |
| `requirements.txt` | The pinned pip dependencies. |
| `input_example.json` | A sample input, if you supplied one. |
The environment files matter later. When Model Serving builds a container for your model, it reads these files to decide which package versions to install.
Flavors
A flavor is a convention for how a model is saved and loaded. MLflow has flavors for scikit-learn, XGBoost, PyTorch, TensorFlow, Hugging Face Transformers and others. Every logged model also gets the generic python_function flavor, usually called pyfunc.
The pyfunc flavor gives every model the same interface: a predict method that takes a pandas DataFrame, a NumPy array or a dictionary, and returns predictions. Serving uses pyfunc, so it does not need special code for each library.
You choose a flavor by calling the matching function: mlflow.sklearn.log_model, mlflow.xgboost.log_model, and so on. This chapter uses the scikit-learn flavor.
Logging a model
The example below trains a random forest on the iris dataset and logs it. It is deliberately small. The same pattern applies to larger models.
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.log_metric("train_accuracy", model.score(X, y))
model_info = mlflow.sklearn.log_model(model, artifact_path="model")
print("Run ID:", run.info.run_id)
print("Model URI:", model_info.model_uri)Here is what each part does:
mlflow.start_run()opens a run. Everything logged inside thewithblock belongs to it. When the block ends, the run is closed.mlflow.log_paramandmlflow.log_metricrecord the settings and a result. They are optional, but logging them next to the model lets you see later how the model was produced.mlflow.sklearn.log_modelserializes the model and uploads the directory described above. Theartifact_pathis the folder name inside the run.- The return value,
model_info, holds the location of the model. Itsmodel_uriis the address you use to load it.
Note that train_accuracy here is computed on the training data, so it is only a demonstration. A real project would log a metric from held-out data.
In a Databricks notebook, MLflow tracking is already configured. The run appears under the notebook's experiment, and you can open it from the Experiments page or from the run link shown in the cell output.
Model URIs
A model URI is a string that points to a logged model. You will see two forms in this tutorial.
runs:/<run_id>/modelpoints to a model inside a run. This is the form you use right after logging.models:/<catalog>.<schema>.<model>/<version>points to a registered model. You will use this form once the model is registered.
The runs:/ form is tied to one run. It is good for testing but is not a stable name for something you want other people or systems to depend on. Registering the model solves that, and later chapters cover it.
Loading the model back
Always load a logged model at least once before you go further. This confirms that the saved artifact is complete.
import mlflow
loaded = mlflow.pyfunc.load_model(model_info.model_uri)
preds = loaded.predict(X.head(5))
print(preds)mlflow.pyfunc.load_model returns a generic wrapper, not your original scikit-learn object. Calling predict on the wrapper is what Model Serving will do. If you need the native object, for example to call predict_proba, use mlflow.sklearn.load_model with the same URI.
The wrapper checks the input against the model's signature when one exists. Adding a signature is the subject of the next chapter. Without one, the wrapper passes your data through and any shape mismatch appears later, often as a confusing error.
Dependencies and environments
When you log a model, MLflow inspects your current environment and records the packages the model needs. This inference is good but not perfect. Common problems:
- Missing packages. If your model's code imports a library in a way MLflow cannot detect, it will be missing from the requirements. The model loads in your notebook but fails in a clean environment.
- Unpinned or mismatched versions. If the serving container installs a different scikit-learn version than the one that trained the model, loading can fail or produce warnings. Unpickling across scikit-learn versions is not guaranteed to work.
- Extra packages. Notebooks often have many libraries installed. MLflow tries to record only what the model needs, but check the recorded file.
You can override the inferred list with the pip_requirements argument:
import mlflow
import sklearn
with mlflow.start_run():
mlflow.sklearn.log_model(
model,
artifact_path="model",
pip_requirements=[f"scikit-learn=={sklearn.__version__}"],
)Pinning the exact version you trained with is a safe habit. Open the logged requirements.txt and read it before you deploy.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `load_model` fails in a new cluster with an import error | A dependency was not recorded in the requirements | Pass `pip_requirements` explicitly and log again |
| Warnings about a version mismatch when loading | The loading environment has a different library version than the training one | Install the version listed in `requirements.txt` |
| Predictions differ between the notebook and the loaded model | The loaded model received differently prepared data, such as another column order | Apply the same preprocessing, or log a pipeline that includes it |
| Model works with a DataFrame but fails with a NumPy array | The model was trained with named columns | Pass a DataFrame with the same column names |
| A run exists but no model artifact appears | `log_model` was never reached, because the code raised an error first | Check the cell output and confirm the call completed |
The preprocessing row deserves special attention. If you scale or encode features before training, the model alone will not reproduce that step. Wrap preprocessing and the estimator together with a scikit-learn Pipeline and log the pipeline. Then the logged artifact accepts raw input.
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=200)),
]).fit(X, y)
with mlflow.start_run():
mlflow.sklearn.log_model(pipeline, artifact_path="model")How the pieces connect
The diagram shows what happens during logging and loading.
The key point is that the model directory is the unit that moves forward. Registration, versioning and serving all act on this directory, not on your notebook code.
Practical guidance
- Log inside a
with mlflow.start_run()block so runs are closed even when an error occurs. - Keep the
artifact_pathconsistent, for example"model", so URIs are predictable. - Record the run ID and model URI. You will need one of them to register the model.
- Test with
mlflow.pyfunc.load_modelbefore moving on. If it fails here, it will fail in serving too. - Prefer a fitted
Pipelineover a bare estimator when preprocessing is involved.
Exercise
You trained a model with a StandardScaler applied by hand to the training data, then logged only the estimator. A teammate loads the logged model and sends raw, unscaled data. Why are the predictions wrong, and how do you fix it?
Show answer
The logged artifact contains only the estimator, so the scaling step is not part of it. The estimator receives unscaled values it never saw during training. Fix this by combining the scaler and estimator in a scikit-learn Pipeline, fitting the pipeline, and logging that. The logged model then applies the scaling itself.
Exercise
After logging a model, you run mlflow.pyfunc.load_model(model_info.model_uri) on a freshly started cluster and get an import error. Which logged file do you inspect first, and which log_model argument can you use to correct it?
Show answer
Inspect requirements.txt (or conda.yaml), because the import error suggests a dependency was not recorded. Correct it by passing the pip_requirements argument to log_model with the needed packages and versions, then log the model again.