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.pswp.cn/pingmian/76902.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/76902.shtml
英文地址,請注明出處:http://en.pswp.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,右移 回到目錄 下一…