MLflow【部署 01】MLflow官网Quick Start实操安装、模型训练、数据预测(一篇学会部署使用MLflow)

本文介绍了如何在5分钟内使用MLflow进行模型部署,包括版本选择、环境配置、追踪服务器启动、模型训练与日志、注册与加载,以及使用Python函数进行推理。详细步骤从安装开始,到在Iris数据集上训练模型并记录到MLflowUI展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Learn in 5 minutes how to log,register,and load a model for inference. 在5分钟内学习如何记录、注册和加载模型用于推理。

1.版本及环境

本文基于2.9.2版本进行说明,内容来自官方文档:https://www.mlflow.org/docs/2.9.2/getting-started/intro-quickstart/index.html,测试环境说明:

# 1.服务器系统版本
CentOS Linux release 7.9.2009 (Core)

# 2.使用conda创建的虚拟环境【conda create -n mlflow python=3.8】
(mlflow) [root@tcloud /]# python -V
Python 3.8.18

2.官方步骤

Step 1 - Get MLflow

# 官方步骤
pip install mlflow

# 实际操作【限制版本 否则会安装最新版本】
pip install mlflow==2.9.2

Step 2 - Start a Tracking Server

# 官方步骤
mlflow server --host 127.0.0.1 --port 8080
# 启动日志【删除了时间信息】
[5027] [INFO] Starting gunicorn 21.2.0
[5027] [INFO] Listening at: http://127.0.0.1:8080 (5027)
[5027] [INFO] Using worker: sync
[5030] [INFO] Booting worker with pid: 5030
[5031] [INFO] Booting worker with pid: 5031
[5032] [INFO] Booting worker with pid: 5032
[5033] [INFO] Booting worker with pid: 5033

# 实际操作【使用的是腾讯云服务器】
mlflow server --host 0.0.0.0 --port 9090
# 启动日志【删除了时间信息】
[13020] [INFO] Starting gunicorn 21.2.0
[13020] [INFO] Listening at: http://0.0.0.0:9090 (13020)
[13020] [INFO] Using worker: sync
[13023] [INFO] Booting worker with pid: 13023
[13024] [INFO] Booting worker with pid: 13024
[13025] [INFO] Booting worker with pid: 13025
[13026] [INFO] Booting worker with pid: 13026
  • –host 0.0.0.0 to listen on all network interfaces (or a specific interface address).

启动后,访问http://<host>:<port>可查看到页面:

image.png

如果使用的是 Databricks 未提供的托管 MLflow 跟踪服务器,或者运行本地跟踪服务器,请确保使用以下命令设置跟踪服务器的 URI:

import mlflow

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

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

Step 3 - Train a model and prepare metadata for logging

在本部分中,我们将使用 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)

Step 4 - Log the model and its metadata to MLflow

这个步骤将使用我们训练的模型、为模型拟合指定的超参数,以及通过评估模型对要记录到 MLflow 的测试数据的性能来计算的损失指标。步骤如下:

  • 启动 MLflow 运行上下文以启动新运行,我们将模型和元数据记录到该运行。
  • 记录模型参数和性能指标。
  • 标记运行以便于检索。
  • 在记录(保存)模型时,在 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",
    )

Step 5 - Load the model as a Python Function (pyfunc) and use it for inference

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

  • 使用 MLflow 的 pyfunc 风格加载模型。
  • 使用加载的模型对新数据运行 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]

Step 6 - View the Run in the MLflow UI

官方带注释的示例:


实际执行示例:

image.png
官方运行详情图片:


实际运行详情图片:

image.png
查看生成的模型:

image.png
恭喜你完成了 MLflow 跟踪快速入门!

3.模型使用

模型文件可以从MLflow的页面上下载,调用代码如下:

import pickle

from sklearn import datasets
from sklearn.model_selection import train_test_split

# 使用鸢尾数据集
# 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)

# 使用自己收集的数据
# X_test = [[5.1, 3.5, 1.4, 0.2], [7, 3.2, 4.7, 1.4], [5.8, 2.7, 5.1, 1.9], [5, 3.4, 1.5, 0.2]]

# 加载模型文件
with open('model.pkl', 'rb') as f:
    model = pickle.load(f)

# 预测类别
predict_res = model.predict(X_test)
print(predict_res)
# 类别的概率值
predict_proba_res = model.predict_proba_res(X_test)
print(predict_proba_res)

运行结果:

[1 0 2 1 1 0 1 2 1 1 2 0 0 0 0 1 2 1 1 2 0 2 0 2 2 2 2 2 0 0]
[[3.78540528e-03 8.27210036e-01 1.69004558e-01]
 [9.46727168e-01 5.32726324e-02 1.99986485e-07]
 [8.72385678e-09 1.55691543e-03 9.98443076e-01]
 [6.43448541e-03 7.92126720e-01 2.01438794e-01]
 [1.44095504e-03 7.74344678e-01 2.24214367e-01]
 [9.55768195e-01 4.42316282e-02 1.76849618e-07]
 [7.76122925e-02 9.08082089e-01 1.43056184e-02]
 [1.61401761e-04 1.55690379e-01 8.44148220e-01]
 [2.20736358e-03 7.62834309e-01 2.34958328e-01]
 [2.83154097e-02 9.45798683e-01 2.58859075e-02]
 [4.39679072e-04 2.43281233e-01 7.56279088e-01]
 [9.68307933e-01 3.16919884e-02 7.80649442e-08]
 [9.72933931e-01 2.70660354e-02 3.33361479e-08]
 [9.62096918e-01 3.79029707e-02 1.10921553e-07]
 [9.79272618e-01 2.07273173e-02 6.47441645e-08]
 [4.54276481e-03 7.12605196e-01 2.82852039e-01]
 [7.22631014e-06 2.42037680e-02 9.75789006e-01]
 [2.73294494e-02 9.47693264e-01 2.49772862e-02]
 [8.23322627e-03 8.31120340e-01 1.60646433e-01]
 [1.41951887e-05 3.59416995e-02 9.64044105e-01]
 [9.64370490e-01 3.56293171e-02 1.92868716e-07]
 [1.31386507e-03 3.99100235e-01 5.99585900e-01]
 [9.61627956e-01 3.83717831e-02 2.61167666e-07]
 [1.85433787e-05 4.58639912e-02 9.54117465e-01]
 [1.63757839e-06 2.58619974e-02 9.74136365e-01]
 [9.32586134e-05 1.05067524e-01 8.94839218e-01]
 [8.68953654e-06 5.83511361e-02 9.41640174e-01]
 [4.29911372e-06 1.88516061e-02 9.81144095e-01]
 [9.66838022e-01 3.31618418e-02 1.35794380e-07]
 [9.56304600e-01 4.36951677e-02 2.32419972e-07]]

4.总结

  • 安装简单
  • 快速入门不难
  • 能够灵活应用需要进行更多的学习

5.更新日志

  • 20240223 添加模型加载、数据预测代码
训练好的 YOLOv5 模型部署到 Qt 上,可以分为两个步骤: 1. 将 YOLOv5 模型转换成 Qt 支持的格式。Qt 支持的模型格式包括 TensorFlow Lite、ONNX 和 Caffe。如果你的模型是 PyTorch 的,可以先将其转换为 ONNX 格式,再使用 ONNX 转换器将其转换为 Qt 支持的格式。 2. 在 Qt 中加载模型并进行推理。Qt 提供了一个名为 QML 的框架,可以在其中加载模型并进行推理。使用 QML,你可以轻松地将模型集成到 Qt 应用程序中,并将其与其他 Qt 控件(如按钮、文本框等)一起使用。 以下是一个简单的示例代码,演示了如何在 Qt 中加载 YOLOv5 模型并进行推理: ```qml import QtQuick 2.15 import QtQuick.Controls 2.15 import QtQuick.Layouts 1.12 import QtQuick.Window 2.15 import QtQuick.Dialogs 1.3 import QtQuick.Controls.Material 2.15 import Qt.labs.platform 1.0 import TensorFlowLite 1.0 Page { id: page title: "YOLOv5 Demo" ColumnLayout { id: layout Text { text: "选择要识别的图像:" } FileDialog { id: fileDialog title: "选择图像" nameFilters: ["Images (*.png *.jpg *.bmp)"] selectMultiple: false onAccepted: { image.source = fileUrl.toString() predict(fileUrl.toString()) } } Image { id: image width: 512 height: 512 fillMode: Image.PreserveAspectFit source: "" MouseArea { anchors.fill: parent onClicked: { fileDialog.open() } } } Text { id: prediction text: "" } } TensorFlowLiteModel { id: model modelFilePath: "yolov5.tflite" } function predict(imagePath) { var inputTensor = model.inputTensor(0) var outputTensor = model.outputTensor(0) // Load image into a tensor var imageData = loadImage(imagePath) inputTensor.data = imageData // Run inference model.invoke() // Parse output var predictions = parseOutput(outputTensor) // Display predictions var predictionText = "Predictions:" for (var i = 0; i < predictions.length; ++i) { predictionText += "\n" + predictions[i].class + ": " + predictions[i].confidence } prediction.text = predictionText } function loadImage(imagePath) { // Load image into a tensor var image = Qt.labs.platform.resourceUrl(imagePath).toLocalFile() var imageObject = new Image() imageObject.source = image var canvas = document.createElement("canvas") canvas.width = imageObject.width canvas.height = imageObject.height var ctx = canvas.getContext("2d") ctx.drawImage(imageObject, 0, 0) var imageData = ctx.getImageData(0, 0, imageObject.width, imageObject.height) var imageTensor = new Float32Array(imageData.data.length) for (var i = 0; i < imageData.data.length; i += 4) { imageTensor[i + 0] = imageData.data[i + 0] / 255 imageTensor[i + 1] = imageData.data[i + 1] / 255 imageTensor[i + 2] = imageData.data[i + 2] / 255 } return imageTensor } function parseOutput(outputTensor) { // Parse output tensor var output = outputTensor.data() var numPredictions = output[0] var predictions = [] for (var i = 0; i < numPredictions; ++i) { var classIndex = output[i * 6 + 1] var confidence = output[i * 6 + 2] var x = output[i * 6 + 3] var y = output[i * 6 + 4] var w = output[i * 6 + 5] var h = output[i * 6 + 6] predictions.push({class: classIndex, confidence: confidence, x: x, y: y, w: w, h: h}) } return predictions } } ``` 上述代码中,我们使用 TensorFlowLiteModel 组件加载并运行 YOLOv5 模型。在 predict 函数中,我们将图像加载到输入张量中,并在模型中运行推理。然后,我们解析输出张量,并将预测结果显示在 UI 中。
评论 24
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yuanzhengme.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值