Lesson 2 of 5
Package and Register the Trained Model
Save the trained model in a standard format and register it in MLflow's model registry so other programs can load it by name and version.
7 minMLOps
After this lesson, you will be able to save a trained model in MLflow's standard format, register it in the model registry, and load it back by name and version.
Why package a model?
A model in a notebook or script is just an object in memory. To serve it later, you need to save it to disk in a format that other programs can load. MLflow provides a standard way to save models from many machine learning libraries, along with metadata about how to run them.
You will continue with the train.py script from lesson 1. It trains a random forest on the iris dataset and logs the accuracy. Now you will add code to save the model and register it.
Save the model with MLflow
MLflow can log a model as an artifact of a run. The model is stored in a directory with a standard layout. Add these lines inside the with mlflow.start_run(): block, after logging the metric:
mlflow.sklearn.log_model(model, "model")The first argument is the trained model object. The second is the artifact path, a subdirectory inside the run's artifact location. MLflow will save the model using its built-in support for scikit-learn.
Run the script:
python train.pyAfter the run, MLflow stores the model under the run's artifacts. You can see it in the MLflow UI under the run's artifacts section.
Register the model
A saved model is tied to a specific run. To make it easy to find and load by name, register it in the MLflow model registry. The registry keeps track of versions of a named model.
Add this line after mlflow.sklearn.log_model:
mlflow.register_model("runs:/<run_id>/model", "iris_classifier")Replace <run_id> with the actual run ID. You can get the run ID from the MLflow UI or by capturing the run object. A cleaner way is to use the active run:
run_id = mlflow.active_run().info.run_id
mlflow.register_model(f"runs:/{run_id}/model", "iris_classifier")The first argument is the model URI, which points to the logged model. The second is the name you want to register it under. If the name does not exist, MLflow creates it and assigns version 1. If it exists, MLflow creates a new version.
The full train.py now looks like this:
import argparse
import pandas as pd
import mlflow
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
def load_data():
iris = load_iris()
X = pd.DataFrame(iris.data, columns=iris.feature_names)
y = iris.target
return X, y
def train_model(X, y, n_estimators):
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = RandomForestClassifier(n_estimators=n_estimators, random_state=42)
model.fit(X_train, y_train)
accuracy = accuracy_score(y_test, model.predict(X_test))
return model, accuracy
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--n_estimators", type=int, default=100)
args = parser.parse_args()
mlflow.set_experiment("iris_classification")
with mlflow.start_run():
X, y = load_data()
mlflow.log_param("n_estimators", args.n_estimators)
model, accuracy = train_model(X, y, args.n_estimators)
mlflow.log_metric("accuracy", accuracy)
mlflow.sklearn.log_model(model, "model")
run_id = mlflow.active_run().info.run_id
mlflow.register_model(f"runs:/{run_id}/model", "iris_classifier")
print(f"Accuracy: {accuracy:.4f}")Run the script again. It will log the model and register it. If you run it multiple times, each run creates a new version of iris_classifier.
Load a registered model
To use the registered model in another program, load it by name and version. Create a new file called load_model.py:
import mlflow
model = mlflow.sklearn.load_model("models:/iris_classifier/1")
print(model)The URI models:/iris_classifier/1 means version 1 of the registered model named iris_classifier. MLflow downloads the model artifacts and reconstructs the scikit-learn object.
Run it:
python load_model.pyYou should see the random forest object printed. This confirms the model can be loaded outside the training script.
Use the model for prediction
You can now use the loaded model to make predictions. Extend load_model.py to load the iris dataset and predict on a few samples:
import mlflow
from sklearn.datasets import load_iris
model = mlflow.sklearn.load_model("models:/iris_classifier/1")
iris = load_iris()
X = iris.data[:5]
predictions = model.predict(X)
print(predictions)Run it:
python load_model.pyThe output is an array of predicted class labels for the first five samples.
Manage versions
Each time you register a model with the same name, MLflow increments the version number. You can load a specific version by changing the number in the URI. To load the latest version, use models:/iris_classifier/latest.
In the MLflow UI, under the Models tab, you can see all registered models and their versions. You can also transition versions to stages like Staging or Production, but for this course you will use version numbers directly.
Key takeaways
- Use
mlflow.sklearn.log_modelto save a trained model as a run artifact. - Register a logged model with
mlflow.register_modelusing a run URI and a model name. - Load a registered model by name and version with
mlflow.sklearn.load_modeland themodels:/URI. - Each registration of the same model name creates a new version, and you can load any version or the latest.
Try it
Modify train.py to register the model under a different name, such as iris_classifier_v2. Run the script once. Then create a new script predict_loaded.py that loads the latest version of iris_classifier_v2, loads the iris dataset, and prints the accuracy of the loaded model on the full dataset. A good result is the script running without errors and printing an accuracy value close to the one logged during training.
Official documentation
Written with AI and checked automatically. Tools change, so a command may behave differently in the version you install. Spotted a mistake? Tell us.