MLflow 跟踪快速入门
欢迎来到 MLflow!
本快速入门旨在提供 MLflow 跟踪核心 API 的核心指南。具体来说,它涵盖了用于模型推理的日志记录、注册和加载等功能。
如果您偏好更深入、基于教程的方法,请参阅 MLflow 入门教程。我们建议您先从这里开始,因为本快速入门使用了 MLflow 跟踪中最常用和最频繁使用的 API,可以为文档中的其他教程打下良好的基础。
您将学到什么
通过本快速入门,您将在几分钟内学会
- 如何记录参数、指标和模型
- MLflow 链式 API 的基础知识
- 如何在记录时注册模型
- 如何在MLflow UI 中导航到模型
- 如何加载已记录的模型以进行推理
如果您更愿意查看本教程的 Jupyter Notebook 版本,请点击以下链接
查看 Notebook第一步 - 获取 MLflow
MLflow 可在 PyPI 上找到。
安装稳定版
如果您尚未在系统中安装 MLflow,可以使用以下命令进行安装:
pip install mlflow
安装候选发布版 (RC)
如果您渴望尝试新功能并验证 MLflow 的即将发布的版本是否能在您的基础设施中正常运行,安装最新的候选发布版可能会引起您的兴趣。
候选发布版不建议用于实际使用,仅供测试验证。
要安装特定版本的 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
第二步 - 启动跟踪服务器
使用托管的 MLflow 跟踪服务器
有关使用托管 MLflow 跟踪服务器的选项的详细信息,包括如何创建具有托管 MLflow 的 Databricks 免费试用帐户,请参阅跟踪服务器选项指南。
运行本地跟踪服务器
我们将启动一个本地 MLflow 跟踪服务器,用于记录本快速入门中的数据。在终端中运行:
mlflow server --host 127.0.0.1 --port 8080
您可以选择任何您想要的端口,只要它未被使用即可。
设置跟踪服务器 URI(如果未使用 Databricks 托管的 MLflow 跟踪服务器)
如果您使用的是非 Databricks 提供的托管 MLflow 跟踪服务器,或者您正在运行本地跟踪服务器,请确保使用以下命令设置跟踪服务器的 URI:
import mlflow
mlflow.set_tracking_uri(uri="http://<host>:<port>")
如果在您的笔记本电脑或运行时环境中未设置此项,运行记录将保存在您的本地文件系统中。
第三步 - 训练模型并准备要记录的元数据
在本节中,我们将使用 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
# 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,
"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)
第四步 - 将模型及其元数据记录到 MLflow
在下一步中,我们将使用训练好的模型、为模型拟合指定的超参数以及通过评估模型在测试数据上的性能计算出的损失指标来记录到 MLflow。
我们将采取以下步骤:
- 初始化 MLflow 运行上下文以开始一个新的运行,我们将在此运行中记录模型和元数据。
- 记录模型参数和性能指标。
- 为运行打标签以便轻松检索。
- 在记录(保存)模型的同时,在 MLflow 模型注册表中注册该模型。
虽然将整个代码包装在 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"}
)
运行上述代码时,您将看到类似以下的控制台输出:
2025/09/09 17:22:20 ERROR mlflow.webhooks.delivery: Failed to deliver webhook for event registered_model.created: FileStore does not support list_webhooks_by_event
Traceback (most recent call last):
...
NotImplementedError: FileStore does not support list_webhooks_by_event
您可以忽略这些错误。它们将在 MLflow 4 中消失,在此之前不会得到修复。
第五步 - 将模型加载为 Python 函数 (pyfunc) 并用于推理
记录模型后,我们可以通过以下方式进行推理:
- 使用 MLflow 的
pyfunc格式加载模型。 - 使用加载的模型在新数据上运行预测。
我们用于 Iris 训练的数据是 NumPy 数组结构。但是,我们也可以像下面这样向 predict 方法提交 Pandas DataFrame。
# 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) | 实际类别 | 预测类别 |
|---|---|---|---|---|---|
| 6.1 | 2.8 | 4.7 | 1.2 | 1 | 1 |
| 5.7 | 3.8 | 1.7 | 0.3 | 0 | 0 |
| 7.7 | 2.6 | 6.9 | 2.3 | 2 | 2 |
| 6.0 | 2.9 | 4.5 | 1.5 | 1 | 1 |
第六步 - 在 MLflow UI 中查看运行和模型
为了查看我们的运行结果,我们可以导航到 MLflow UI。由于我们已经在https://:8080 启动了跟踪服务器,我们只需在浏览器中导航到该 URL 即可。
打开网站时,您将看到一个类似以下的屏幕:
点击我们创建的实验名称(“MLflow Quickstart”)将显示与该实验关联的运行列表。您应该会在右侧的 Table 列表视图中看到一个生成的随机运行名称,而没有其他内容。
点击运行名称将带您进入运行页面,其中显示了我们记录的内容的详细信息。下面高亮显示了这些元素,以展示数据是如何以及在哪里在 UI 中记录的。
在实验页面切换到 Models 选项卡,以查看实验下所有已记录的模型,您将看到我们刚刚创建的已记录模型(“tracking-quickstart”)的条目。
点击模型名称将带您进入已记录模型页面,其中包含已记录模型及其元数据的详细信息。
结论
恭喜您完成了 MLflow 跟踪快速入门!您现在应该对如何使用 MLflow 跟踪 API 来记录模型有了基本的了解。
如果您对更深入的教程感兴趣,请参阅 MLflow 入门教程,这是您进一步学习 MLflow 的一个好步骤!