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

news2024/9/22 4:04:25

一篇学会部署使用MLflow

  • 1.版本及环境
  • 2.官方步骤
    • Step 1 - Get MLflow
    • Step 2 - Start a Tracking Server
    • Step 3 - Train a model and prepare metadata for logging
    • Step 4 - Log the model and its metadata to MLflow
    • Step 5 - Load the model as a Python Function (pyfunc) and use it for inference
    • Step 6 - View the Run in the MLflow UI
  • 3.模型使用
  • 4.总结
  • 5.更新日志

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 添加模型加载、数据预测代码

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1464499.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

yolov5导出onnx转engine推理

yolov5导出注意事项 配置 需要提供配置文件和权重文件&#xff0c;不然导出模型不能正常推理。 默认提供检测头。 ModuleNotFoundError: No module named ‘tensorrt’安装TensorRT-python发现报错 由于ModuleNotFoundError: No module named ‘tensorrt’安装TensorRT-pyt…

备战蓝桥杯—— 双指针技巧巧答链表1

对于单链表相关的问题&#xff0c;双指针技巧是一种非常广泛且有效的解决方法。以下是一些常见问题以及使用双指针技巧解决&#xff1a; 合并两个有序链表&#xff1a; 使用两个指针分别指向两个链表的头部&#xff0c;逐一比较节点的值&#xff0c;将较小的节点链接到结果链表…

【学习iOS高质量开发】——协议与分类

文章目录 一、通过委托与数据源协议进行对象间通信1.委托模式2.要点 二、将类的实现代码分散到便于管理的数个分类之中1.如何实现2.要点 三、总是为第三方类的分类名称加前缀1.为什么总是为第三方类的分类名称加前缀2.要点 三、勿在分类中声明属性1.勿在分类中声明属性的原因2.…

OpenAI文生视频大模型Sora概述

Sora&#xff0c;美国人工智能研究公司OpenAI发布的人工智能文生视频大模型&#xff08;但OpenAI并未单纯将其视为视频模型&#xff0c;而是作为“世界模拟器” &#xff09;&#xff0c;于2024年2月15日&#xff08;美国当地时间&#xff09;正式对外发布。 Sora可以根据用户…

三维测量技术及应用

接触式测量&#xff08;Contact Measurement&#xff09;&#xff1a; 坐标测量机&#xff08;CMM, Coordinate Measuring Machine&#xff09;&#xff1a;通过探针直接接触物体表面获取三维坐标数据。优点是精度高&#xff0c;但速度慢&#xff0c;对软质材料测量效果不佳&am…

qt 软件发布(Windows)

1. 开发环境 QtCreator MSVC编译器 2. 源码编译 生成release或者debug版本的exe可执行文件(x64或x86) 3. windeployqt 打包 ①左下角开始菜单栏找到QT的命令交互对话框&#xff0c;如下图MSVC 2017 64-bit(根据第二步编译的类型选择64位或者32位)。 ②cd 切换到第二步可…

igolang学习2,golang开发配置国内镜像

go env -w GO111MODULEon go env -w GOPROXYhttps://goproxy.cn,direct

杂题——1097: 蛇行矩阵

题目描述 蛇形矩阵是由1开始的自然数依次排列成的一个矩阵上三角形。 输入格式 本题有多组数据&#xff0c;每组数据由一个正整数N组成。&#xff08;N不大于100&#xff09; 输出格式 对于每一组数据&#xff0c;输出一个N行的蛇形矩阵。两组输出之间不要额外的空行。矩阵三角…

【算法与数据结构】841、LeetCode钥匙和房间

文章目录 一、题目二、解法三、完整代码 所有的LeetCode题解索引&#xff0c;可以看这篇文章——【算法和数据结构】LeetCode题解。 一、题目 二、解法 思路分析&#xff1a;   程序如下&#xff1a; 复杂度分析&#xff1a; 时间复杂度&#xff1a; O ( ) O() O()。空间复杂…

VR系统的开发流程

虚拟现实&#xff08;Virtual Reality&#xff0c;VR&#xff09;系统是一种通过计算机技术模拟出的具有三维视角和交互性的虚拟环境&#xff0c;使用户能够沉浸在其中并与虚拟环境进行交互。这种技术通常利用头戴式显示器和手柄等设备&#xff0c;使用户能够感觉到仿佛身临其境…

(全注解开发)学习Spring-MVC的第三天

全注解开发 第一部分 : 1.1 消除spring-mvc.xml 这些是原来spring-mvc.xml配置文件的内容 <!--1、组件扫描, 使Controller可以被扫描到--><context:component-scan base-package"com.itheima.controller"/><!--2、非自定义的Bean, 文件上传解析器--&…

mysql优化指南之优化篇

二、优化 现在的理解数据库优化有四个维度&#xff0c;分别是&#xff1a; 硬件升级、系统配置、表结构设计、SQL语句及索引。 那优化的成本和效果分别如下&#xff1a; 优化成本&#xff1a;硬件升级>系统配置>表结构设计>SQL语句及索引。 优化效果&#xff1a;…

编码器AB信号输入脉冲信号测量2路DI高速计数器PNP/NPN转RS-485数据采集模块 YL150-485

特点&#xff1a; ● 编码器解码转换成标准Modbus RTU协议 ● 可用作编码器计数器或者转速测量 ● 支持编码器计数&#xff0c;可识别正反转 ● 也可以设置作为2路独立DI高速计数器 ● 计数值支持断电自动保存 ● DI输入支持PNP和NPN输入 ● 继电器和机械开关输入时可以…

【AI应用】SoraWebui——在线文生视频工具

SoraWebui 是一个开源项目&#xff0c;允许用户使用 OpenAI 的 Sora 模型使用文本在线生成视频&#xff0c;从而简化视频创建&#xff0c;并具有轻松的一键网站部署功能 在 Vercel 上部署 1. 克隆项目 git clone gitgithub.com:SoraWebui/SoraWebui.git 2. 安装依赖 cd Sor…

flutter开发实战-手势Gesture与ListView滚动竞技场的可滑动关闭组件

flutter开发实战-手势Gesture与ListView滚动竞技场的可滑动关闭组件 最近看到了一个插件&#xff0c;实现一个可滑动关闭组件。滑动关闭组件即手指向下滑动&#xff0c;组件随手指移动&#xff0c;当移动一定位置时候&#xff0c;手指抬起后组件滑出屏幕。 一、GestureDetect…

数据安全治理实践路线(上)

基于以上数据安全治理实践理念&#xff0c;可以按照自顶向下和自底向上相结合的思路推进实践过程。一方面&#xff0c;组织自顶向下,以数据安全战略规划为指导,以规划、建设、运营、优化为主线&#xff0c;围绕构建数据安全治理体系这一核心&#xff0c;从组织架构、制度流程、…

这份攻略帮助你分分钟构建出“幻兽帕鲁游戏”极致体验【下】

在上一篇文章这份攻略帮助你分分钟构建出“幻兽帕鲁游戏”极致体验【上】中写了&#xff0c;极狐GitLab 将 terraform state 文件管理了起来。这篇文章将演示如何将所有的 terraform 文件存储到极狐GitLab 中&#xff0c;并且使用 CI/CD 自动实现 terraform 命令的执行。 在 D…

HGAME week2 web

1.What the cow say? 测试发现可以反引号命令执行 ls /f* tac /f*/f* 2.myflask import pickle import base64 from flask import Flask, session, request, send_file from datetime import datetime from pytz import timezonecurrentDateAndTime datetime.now(timezone(…

在word中将latex格式的公式转化为带有编号的mathtype公式

在word中将latex格式的公式转化为带有编号的mathtype公式 1.先在word里面配置好mathtype2.在word中设置mathtype的格式3.先将latex格式的公式转化为mathml格式4.读到这里&#xff0c;是不是觉得这个方法麻烦 1.先在word里面配置好mathtype 注意&#xff1a;1.word的版本应该是 …

关于运行flutter app 运行到模拟器出现异常提示

Exception: Gradle task assembleDebug failed with exit code 1 解决方案&#xff1a; 1.讲当前文件的distributionUrl值改为 https://mirrors.cloud.tencent.com/gradle/gradle-7.4-all.zip