跳至主内容

MLflow 跟踪快速入门

欢迎使用 MLflow!

本快速入门的目的是为 MLflow Tracking 最重要的核心 API 提供简明指南。具体而言,介绍那些用于记录、注册和加载模型以进行推理的 API。

note

如果你喜欢更深入、以教程为基础的学习方式,请参阅 Getting Started with MLflow 教程。 不过我们建议你先从这里开始,因为该快速入门使用了最常见、最常用的 MLflow Tracking APIs,并为文档中的其他教程提供了良好的基础。

你将学到什么

只需几分钟,按照本快速入门操作,你将学到:

  • 如何 记录 参数、指标和模型
  • 关于 MLflow fluent API 的基础
  • 如何在日志记录期间注册模型
  • 如何在 MLflow UI 中导航到模型
  • 如何 加载 已记录的模型用于推理
note

如果您想查看本教程的 Jupyter Notebook 版本,请点击以下链接:

查看笔记本

步骤 1 - 获取 MLflow

MLflow 可在 PyPI 上使用。

安装稳定版本

如果你的系统上还没有安装它,你可以使用以下命令安装:

pip install mlflow

安装发布候选版本 (RC)

如果您渴望测试新功能并验证即将发布的 MLflow 版本能否在您的基础设施中良好运行,安装最新的发布候选版本可能会引起您的兴趣。

note

发布候选版本(Release Candidate)不建议用于实际使用,它们仅用于测试验证。

要安装给定版本的 MLflow 的最新发布候选版本,请参见下面以 MLflow 2.14.0 为例的示例:

# install the latest release candidate
pip install --pre mlflow

# or install a specific rc version
pip install mlflow==3.1.0rc0

第 2 步 - 启动跟踪服务器

使用托管的 MLflow 跟踪服务器

有关使用托管 MLflow Tracking Server 的选项的详细信息,包括如何创建包含托管 MLflow 的 Databricks 免费试用帐户,see the guide for tracking server options.

运行本地跟踪服务器

我们将启动一个本地 MLflow 跟踪服务器,并连接到它以记录本快速入门的相关数据。 在终端中运行:

mlflow server --host 127.0.0.1 --port 8080
note

你可以选择任何想要的端口,前提是该端口尚未被占用。

设置跟踪服务器 URI (如果不使用 Databricks 托管的 MLflow 跟踪服务器)

如果您正在使用非 Databricks 提供的托管 MLflow Tracking Server,或者正在运行本地跟踪服务器,请确保使用以下方式设置跟踪服务器的 uri:

import mlflow

mlflow.set_tracking_uri(uri="http://<host>:<port>")

如果未在您的笔记本或运行时环境中设置此项,运行将记录到您的本地文件系统。

第3步 - 训练模型并准备用于记录的元数据

在本节中,我们将使用 MLflow 记录一个模型。步骤的简要概述如下:

  • 加载并准备 Iris 数据集以进行建模。
  • 训练一个逻辑回归模型并评估其性能。
  • 准备模型的超参数并计算要记录的指标。
import mlflow
from mlflow.models import infer_signature

import pandas as pd
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score


# Load the Iris dataset
X, y = datasets.load_iris(return_X_y=True)

# Split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)

# Define the model hyperparameters
params = {
"solver": "lbfgs",
"max_iter": 1000,
"multi_class": "auto",
"random_state": 8888,
}

# Train the model
lr = LogisticRegression(**params)
lr.fit(X_train, y_train)

# Predict on the test set
y_pred = lr.predict(X_test)

# Calculate metrics
accuracy = accuracy_score(y_test, y_pred)

步骤 4 - 将模型及其元数据记录到 MLflow

在下一步中,我们将使用我们训练的模型、为模型的 fit 指定的超参数,以及通过在测试数据上评估模型性能计算出的损失指标,将这些记录到 MLflow。

我们将采取的步骤如下:

  • 开启 MLflow run 上下文以启动一个新的 run,我们将把模型和元数据记录到该 run 中。
  • 记录 模型 参数 和 性能 指标
  • 标记 该运行以便于检索。
  • 在将模型 注册 到 MLflow Model Registry 的同时 记录(保存)该模型。
note

尽管将整个代码包裹在 start_run 块内是可行的,但这不推荐。如果模型训练或与 MLflow 相关操作无关的任何其他代码部分发生问题,将会创建一个空的或部分记录的运行,这将需要手动清理该无效运行。最好将训练执行保持在运行上下文块之外,以确保可记录的内容(参数、指标、工件和模型)在记录之前完全生成。

# Set our tracking server uri for logging
mlflow.set_tracking_uri(uri="http://127.0.0.1:8080")

# Create a new MLflow Experiment
mlflow.set_experiment("MLflow Quickstart")

# Start an MLflow run
with mlflow.start_run():
# Log the hyperparameters
mlflow.log_params(params)

# Log the loss metric
mlflow.log_metric("accuracy", accuracy)

# Infer the model signature
signature = infer_signature(X_train, lr.predict(X_train))

# Log the model, which inherits the parameters and metric
model_info = mlflow.sklearn.log_model(
sk_model=lr,
name="iris_model",
signature=signature,
input_example=X_train,
registered_model_name="tracking-quickstart",
)

# Set a tag that we can use to remind ourselves what this model was for
mlflow.set_logged_model_tags(
model_info.model_id, {"Training Info": "Basic LR model for iris data"}
)

步骤 5 - 将模型作为 Python 函数 (pyfunc) 加载并用于推理

记录模型后,我们可以通过以下方式执行推理:

  • 正在加载模型,使用 MLflow 的 pyfunc flavor。
  • 使用已加载的模型在新数据上运行 Predict
note

我们使用的 iris 训练数据是一个 numpy 数组结构。然而,我们也可以将一个 Pandas DataFrame 提交给 predict 方法,如下所示。

# Load the model back for predictions as a generic Python Function model
loaded_model = mlflow.pyfunc.load_model(model_info.model_uri)

predictions = loaded_model.predict(X_test)

iris_feature_names = datasets.load_iris().feature_names

result = pd.DataFrame(X_test, columns=iris_feature_names)
result["actual_class"] = y_test
result["predicted_class"] = predictions

result[:4]

这段代码的输出将类似于:

花萼长度 (cm)花萼宽度 (cm)花瓣长度 (cm)花瓣宽度 (cm)actual_classpredicted_class
6.12.84.71.211
5.73.81.70.300
7.72.66.92.322
6.02.94.51.511

步骤 6 - 在 MLflow UI 中查看运行和模型

为了查看我们的运行结果,我们可以访问 MLflow UI。由于我们已经在 http://localhost:8080 启动了 Tracking Server,所以只需在浏览器中打开该 URL。

打开该站点时,您会看到如下类似的界面:

MLflow UI Experiment view page

The main MLflow Tracking page, showing Experiments that have been created

点击我们创建的 Experiment 的名称(“MLflow Quickstart”)会显示与该 Experiment 关联的运行列表。你应该会在右侧的 Table 列表视图中看到为该运行生成的一个随机名称,除此之外不会显示其他内容。

点击运行名称将带您到 Run 页面,那里会显示我们记录的详细信息。下面突出显示了各个元素,以展示这些数据在用户界面中的记录位置和方式。

MLflow UI Run view page

The run view page for our run

切换到实验页面的 Models 选项卡,以查看该实验下记录的所有模型,您可以看到我们刚创建的记录模型 ("iris_model") 的一个条目。

MLflow UI Experiment view page models tab

The models tab of the MLflow Tracking page, showing a list of all models created

单击模型名称将带您进入“已记录模型”页面,页面显示已记录模型及其元数据的详细信息。

MLflow UI Model view page

The model view page for our logged model

结论

恭喜你完成 MLflow Tracking 快速入门!你现在应该已经基本了解如何使用 MLflow Tracking API 来记录模型。

如果您对更深入的教程感兴趣,请参阅 Getting Started with MLflow 教程,作为提升您对 MLflow 知识的良好下一步!