MLflow 入门

  • 官方主页 MLflow | MLflow
  • 官方文档 MLflow: A Tool for Managing the Machine Learning Lifecycle | MLflow

0. 简介

MLflow 是一个开源平台,专门为了帮助机器学习的从业者和团队处理机器学习过程中的复杂性而设计。MLflow 关注机器学习项目的完整生命周期,确保每个阶段都是可管理的、可追溯的和可复现的。

MLflow 目前提供了几个关键的组件:

MLflow AI Gateway:通过安全、简单的API与最先进的 LLM 进行交互。
MLflow LLM Evaluate:简化LLM和提示的评估。
MLflow Tracking:记录和查询实验:代码、数据、配置和结果。
MLflow Projects:将数据科学代码打包成一种格式,可以在任何平台上重现运行。
MLflow Models:在不同的服务环境中部署机器学习模型。
Model Registry:在一个中心仓库中存储、注释、发现和管理模型。

1. 安装 MLFlow

pip install mlflow

2. 启动 Tracking UI

mlflow server --host 127.0.0.1 --port 8080

 端口可以任意指定一个本地可用端口即可。

浏览器输入 http://localhost:5000 访问:

3. 创建实验

这里的实验类似于我们的project,独立的实验可以方便进行管理和查看 

from mlflow import MlflowClient
client = MlflowClient(tracking_uri="http://127.0.0.1:8080")
all_experiments = client.search_experiments()default_experiment = [{"name": experiment.name, "lifecycle_stage": experiment.lifecycle_stage}for experiment in all_experimentsif experiment.name == "Default"
][0]
# Provide an Experiment description that will appear in the UI
experiment_description = ("This is the grocery forecasting project. ""This experiment contains the produce models for apples."
)# Provide searchable tags that define characteristics of the Runs that
# will be in this Experiment
experiment_tags = {"project_name": "grocery-forecasting","store_dept": "produce","team": "stores-ml","project_quarter": "Q3-2023","mlflow.note.content": experiment_description,
}# Create the Experiment, providing a unique name
produce_apples_experiment = client.create_experiment(name="Apple_Models", tags=experiment_tags
)

在 Tracking UI 里面可以看到刚创建的实验。

4. Model准备

下面是一个逻辑回归的模型。

import mlflow
from mlflow.models import infer_signatureimport 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)


5. Model记录

下面我们添加 MLflow 代码,记录模型信息。

import mlflow
from mlflow.models import infer_signatureimport 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)
这里训练好了一个逻辑回归的模型。Model记录
import mlflow
from mlflow.models import infer_signatureimport 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)#2nd part code# 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 hyperparametersmlflow.log_params(params)# Log the loss metricmlflow.log_metric("accuracy", accuracy)# Set a tag that we can use to remind ourselves what this run was formlflow.set_tag("Training Info", "Basic LR model for iris data")# Infer the model signaturesignature = infer_signature(X_train, lr.predict(X_train))# Log the modelmodel_info = mlflow.sklearn.log_model(sk_model=lr,artifact_path="iris_model",signature=signature,input_example=X_train,registered_model_name="tracking-quickstart",)

其实也可以把训练模型和其他逻辑的代码放进 start_run 里面,但是官方不建议这么做,因为如果你训练或者其他逻辑代码报错有什么问题,会导致之前出现空或者无效记录,就需要手动去UI里面进行清理了。

设置链接的方式使用的是 mlflow.set_tracking_uri(uri="http://127.0.0.1:8080"),其实还有一种方式 client = MlflowClient(tracking_uri="http://127.0.0.1:8080")。client方式更加灵活,可以一份代码里面有多个跟踪服务器,另一种适合一份代码只有一个跟踪服务器来使用。 

6. 调用Model

import mlflow
from mlflow.models import infer_signatureimport 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)
print(accuracy)# 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 hyperparametersmlflow.log_params(params)# Log the loss metricmlflow.log_metric("accuracy", accuracy)# Set a tag that we can use to remind ourselves what this run was formlflow.set_tag("Training Info", "Basic LR model for iris data")# Infer the model signaturesignature = infer_signature(X_train, lr.predict(X_train))# Log the modelmodel_info = mlflow.sklearn.log_model(sk_model=lr,artifact_path="iris_model",signature=signature,input_example=X_train,registered_model_name="tracking-quickstart",)print(f'{model_info.model_uri}')# Load the model back for predictions as a generic Python Function modelloaded_model = mlflow.pyfunc.load_model(model_info.model_uri)predictions = loaded_model.predict(X_test)iris_feature_names = datasets.load_iris().feature_namesresult = pd.DataFrame(X_test, columns=iris_feature_names)result["actual_class"] = y_testresult["predicted_class"] = predictionsprint(result[:4])

7. 发布模型(Serving)

MLflow 模型发布,可以docker或k8s容器发布。首先介绍最简单的独立发布。
         

首先我们需要配置环境变量 MLFLOW_TRACKING_URI,值为你本地mlflow server启动的地址,默认情况就是http://127.0.0.1:8080。

然后是保证你mlflow中是有记录模型的,然后执行下面命令(需要有flask环境,没有的话需要pip install flask)

mlflow models serve -m models:/{model_name}/{version} --no-conda -p 5001 -h 0.0.0.0

mlflow models serve命令是用来在本地部署一个MLflow模型的。它会启动一个Flask服务器,提供一个REST API来预测模型的输出。这上面的参数来指定了模型的位置,端口号,主机名,以及是否使用conda环境:

-m 或 --model-uri:模型的URI,可以是本地文件系统,S3,Azure ML等。
-p 或 --port:服务器的端口号,默认是5000。
-h 或 --host:服务器的主机名,默认是127.0.0.1。
–no-conda:如果指定了这个参数,那么不会使用conda环境来运行模型,而是使用当前的Python环境。

执行命令之后看到这个输出代表启动成功了

 

mlflow models serve 命令部署模型到本地,只需要访问一个 api,就是 /invocations。这个 api 用于接收模型的输入数据,并返回预测结果。不需要自己定义这个 api,它是由 mlflow 自动生成的。

可以用curl或者postman进行测试

curl -X POST -H "Content-Type:application/json" --data '{"input":[[0,0]]}' http://localhost:5001/invocations


如果想知道是否正常运行的model service,可以call它的/ping routepoint 
如果返回是200的话代表模型正常运行,如果其他状态码就表明有问题了。

参考链接:

https://blog.csdn.net/Damien_J_Scott/article/details/134602472
https://blog.csdn.net/scgaliguodong123_/article/details/124802396

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

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

相关文章

【蓝桥杯选拔赛真题101】Scratch吐丝的蜘蛛 第十五届蓝桥杯scratch图形化编程 少儿编程创意编程选拔赛真题解析

目录 scratch吐丝的蜘蛛 一、题目要求 1、准备工作 2、功能实现 二、案例分析 1、角色分析 2、背景分析 3、前期准备 三、解题思路 四、程序编写 五、考点分析 六、推荐资料 1、scratch资料 2、python资料 3、C++资料 scratch吐丝的蜘蛛 第十五届青少年蓝桥杯s…

智谱最新模型GLM4是如何练成的

写在前面 这篇博客将基于《ChatGLM: A Family of Large Language Models from GLM-130B to GLM-4 All Tools》,深入剖析 GLM-4 系列在**模型架构设计、预训练、后训练(对齐)、以及关键技术创新(如长上下文处理、Agent 能力构建)**等环节的实现逻辑与设计考量,带你全面了…

第二届电气技术与自动化工程国际学术会议 (ETAE 2025)

重要信息 2025年4月25-27日 中国广州 官网: http://www.icetae.com/ 部分 征稿主题 Track 1:电气工程 输配电、电磁兼容、高电压和绝缘技术、电气工程、电气测量、电力电子及其应用、机电一体化、电路与系统、电能质量和电磁兼容性、电力系统及其自…

设备调试--反思与总结

最近回顾项目, 发现:在调试过程中最耽误时间的可能不是技术难度,而是惯性思维; 例如: 我写can通信滤波器的时候,可能是不过滤的;是接收所有的id报文,然后用业务逻辑过滤&#xff08…

C++项目:高并发内存池_下

目录 8. thread cache回收内存 9. central cache回收内存 10. page cache回收内存 11. 大于256KB的内存申请和释放 11.1 申请 11.2 释放 12. 使用定长内存池脱离使用new 13. 释放对象时优化成不传对象大小 14. 多线程环境下对比malloc测试 15. 调试和复杂问题的调试技…

深度学习入门:神经网络的学习

目录 1 从数据中学习1.1 数据驱动1.2 训练数据和测试数据 2损失函数2.1 均方误差2.2 交叉熵误差2.3 mini-batch学习2.4 mini-batch版交叉熵误差的实现2.5 为何要设定损失函数 3 数值微分3.1 数值微分3.3 偏导数 4 梯度4.1 梯度法4.2 神经网络的梯度 5 学习算法的实现5.1 2层神经…

【第45节】windows程序的其他反调试手段上篇

目录 引言 一、通过窗口类名和窗口名判断 二、检测调试器进程 三、父进程是否是Explorer 四、RDTSC/GetTickCount时间敏感程序段 五、StartupInfo结构的使用 六、使用BeingDebugged字段 七、 PEB.NtGlobalFlag,Heap.HeapFlags,Heap.ForceFlags 八、DebugPort:CheckRem…

Golang|select

文章目录 多路监听超时控制 多路监听 如果selcet外面没有for循环,则只会监听一次,要实现一直监听的话要加for循环但是如果要设置退出条件的话,break语句只会退出这个select而不会退出for循环 select也可以有default,用于不用等cha…

无人机的群体协同与集群控制技术要点!

一、技术要点 通信技术 高效可靠的通信链路:无人机集群需要稳定、低延迟的通信网络,以实现实时数据传输和指令交互。通信方式包括无线自组织网络(Ad Hoc)、蜂窝网络、卫星通信等,需根据任务场景选择合适的通信技术。…

新手小白如何给个人电脑安装Deepseek?

准备工作:Ollama安装包、Chatbox安装包 一、安装Ollama 官网下载: 在 Windows 上下载 Ollama:https://ollama.com/download/windows 下载较慢,大家可以自行搜索资源下载,直接双击安装即可。 安装完毕后,…

Redis之RedLock算法以及底层原理

自研redis分布式锁存在的问题以及面试切入点 lock加锁关键逻辑 unlock解锁的关键逻辑 使用Redis的分布式锁 之前手写的redis分布式锁有什么缺点?? Redis之父的RedLock算法 Redis也提供了Redlock算法,用来实现基于多个实例的分布式锁。…

【控制学】控制学分类

【控制学】控制学分类 文章目录 [TOC](文章目录) 前言一、工程控制论1. 经典控制理论2. 现代控制理论 二、生物控制论三、经济控制论总结 前言 控制学是物理、数学与工程的桥梁 提示:以下是本篇文章正文内容,下面案例可供参考 一、工程控制论 1. 经典…

Android 15 中 ApnPreferenceController 的 onStart 和 onStop 调用失效

背景 AOSP对APN入口(Access Point Name)实现中,overried了 onStart 和 onStop ,但实际执行中根本不会进入这两个接口的逻辑。 Q:MobileNetworkSettings (APN入口Preference所在的界面Fragement承载,TAG是NetworkSettings)的生命周期和ApnPreference 有什么关系? Not…

React 在组件间共享状态

在组件间共享状态 有时候,你希望两个组件的状态始终同步更改。要实现这一点,可以将相关 state 从这两个组件上移除,并把 state 放到它们的公共父级,再通过 props 将 state 传递给这两个组件。这被称为“状态提升”,这…

阶段性使用总结-通义灵码

序言 前段时间用通义灵码,参加了下数字中国闽江流域的比赛。https://www.dcic-china.com/competitions/10173 最后成绩一般般,106名,大概有2000多人参加这题目,估计有一堆小号。 按照下面这个思路建模的,迭代了大概15…

游戏引擎学习第228天

对上次的内容进行回顾,并为今天的开发环节做铺垫。 目前大部分功能我们已经完成了,唯一剩下的是一个我们知道存在但目前不会实际触发的 bug。这个 bug 的本质是在某些线程仍然访问一个已经被销毁的游戏模式(mode)之后的状态&…

游戏测试入门知识

高内聚指的是一个模块或组件内部的功能应该紧密相关。这意味着模块内的所有元素都应该致力于实现同一个目标或功能,并且该模块应当尽可能独立完成这一任务。 低耦合则是指不同模块之间的依赖程度较低,即一个模块的变化对其它模块造成的影响尽可能小。理…

L1-2 种钻石

题目 2019年10月29日,中央电视台专题报道,中国科学院在培育钻石领域,取得科技突破。科学家们用金刚石的籽晶片作为种子,利用甲烷气体在能量作用下形成碳的等离子体,慢慢地沉积到钻石种子上,一周“种”出了一…

基于开源技术生态的社群运营温度化策略研究——以“开源链动2+1模式AI智能名片S2B2C商城小程序源码”融合应用为例

摘要 在社交媒体与电商深度融合的背景下,社群运营的“温度化”成为企业构建用户忠诚度的核心命题。本文以康夏社群运营案例为切入点,结合“开源链动21模式AI智能名片S2B2C商城小程序源码”技术架构,分析其通过开源技术实现情感联结与商业价值…

编程技能:调试01,调试介绍

专栏导航 本节文章分别属于《Win32 学习笔记》和《MFC 学习笔记》两个专栏,故划分为两个专栏导航。读者可以自行选择前往哪个专栏。 (一)WIn32 专栏导航 上一篇:编程基础:位运算07,右移 回到目录 下一…