MLflow 追踪快速入门
欢迎使用MLflow!
本快速入门指南旨在提供关于MLflow Tracking最核心API的快速指引。具体来说,是那些支持记录、注册和加载模型以进行推理的API。
如果您更喜欢深入且基于教程的学习方式,请参阅Getting Started with MLflow教程。不过我们建议您先从这里开始,因为本快速入门使用了MLflow Tracking中最常用和频繁使用的API,为文档中的其他教程奠定了良好基础。
你将学习到
只需跟随本快速入门指南几分钟,您将学习到:
- 如何记录参数、指标和模型
- MLflow 流畅API的基础知识
- 如何在日志记录期间注册模型
- 如何在MLflow UI中导航至模型
- 如何加载已记录的模型进行推理
步骤1 - 获取MLflow
MLflow 可在 PyPI 上获取。
安装稳定版本
如果您的系统上尚未安装,可以通过以下命令安装:
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==2.14.0rc0
步骤2 - 启动跟踪服务器
使用托管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>")
如果未在您的笔记本或运行时环境中设置此项,运行记录将被保存到本地文件系统中。
步骤3 - 训练模型并准备记录元数据
在本节中,我们将使用MLflow记录一个模型。以下是步骤的简要概述:
- 加载并准备鸢尾花数据集用于建模。
- 训练一个逻辑回归模型并评估其性能。
- 准备模型超参数并计算需要记录的指标。
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
在下一步中,我们将使用训练好的模型、为模型拟合指定的超参数,以及通过评估模型在测试数据上的性能计算得出的损失指标,将这些信息记录到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)
# Set a tag that we can use to remind ourselves what this run was for
mlflow.set_tag("Training Info", "Basic LR model for iris data")
# Infer the model signature
signature = infer_signature(X_train, lr.predict(X_train))
# Log the model
model_info = mlflow.sklearn.log_model(
sk_model=lr,
artifact_path="iris_model",
signature=signature,
input_example=X_train,
registered_model_name="tracking-quickstart",
)
步骤5 - 将模型加载为Python函数(pyfunc)并用于推理
记录模型后,我们可以通过以下方式进行推理:
- 加载模型使用MLflow的
pyfunc
flavor。 - 使用加载的模型对新数据运行Predict。
我们使用的鸢尾花训练数据是一个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 |
步骤6 - 在MLflow UI中查看运行记录
要查看我们运行的结果,可以导航到MLflow UI界面。由于我们已经在http://localhost:8080启动了跟踪服务器,只需在浏览器中访问该URL即可。
打开网站时,您将看到类似以下的界面:
点击我们创建的实验名称("MLflow Quickstart")将显示与该实验关联的运行列表。您会看到一个为运行随机生成的名称,右侧Table
列表视图中不会显示其他内容。
点击运行名称将跳转至运行页面,这里会显示我们已记录的所有详细信息。下方高亮显示的元素展示了这些数据在用户界面中的记录方式和位置。
结论
恭喜您完成MLflow追踪快速入门!您现在应该对如何使用MLflow追踪API记录模型有了基本理解。
如果您想深入了解更深入的教程,请参阅Getting Started with MLflow教程,这是提升您MLflow知识的良好下一步!