文章目录
一、mlflow有什么用?
MLflow是一个由Databricks公司开发并开源的平台,其主要作用在于帮助数据科学家和工程师有效地管理整个机器学习生命周期。以下是MLflow的详细作用:
1. 实验跟踪(MLflow Tracking)
- 记录和可视化实验:MLflow Tracking允许用户在机器学习实验过程中记录参数、代码版本、指标、模型环境依赖项和模型工件等信息。这些信息可以通过MLflow的UI进行查看和比较,帮助用户理解不同实验之间的差异和效果。
- 提高可复现性:通过记录详细的实验信息,MLflow使得实验结果的可复现性大大提高。用户可以根据记录的参数和代码版本重新运行实验,以验证结果或进行进一步的探索。
2. 项目打包(MLflow Projects)
- 代码打包与共享:MLflow Projects提供了一种标准化的方式来打包和共享数据科学代码。用户可以将代码、数据和环境依赖项打包成一个可重现的项目,方便在不同的环境中进行部署和分享。
- 简化部署流程:通过MLflow Projects,用户可以轻松地将训练好的模型部署到生产环境中,而无需担心环境依赖和配置问题。
3. 模型管理(MLflow Models)
- 模型打包与部署:MLflow Models提供了一种标准化的模型打包格式和工具套件,允许用户将训练好的模型保存为标准格式,并通过多种机制(如Docker、Apache Spark、Databricks、Azure ML、AWS SageMaker等)进行部署和管理。
- 模型版本控制:MLflow还提供了模型版本控制功能,帮助用户管理不同版本的模型,确保在生产环境中使用正确且稳定的模型。
4. 模型注册表(MLflow Model Registry)
- 集中式模型存储:MLflow Model Registry是一个集中式模型存储库,提供了API和用户界面,用于协作管理MLflow模型的整个生命周期。
- 模型审批与质量保证:通过模型注册表,用户可以进行模型的审批和质量保证工作,确保只有符合要求的模型才能被部署到生产环境中。
5. 自动化与集成
- 自动化工作流:MLflow可以与许多流行的ML库和工具集成,并支持自动化工作流的创建和执行。这有助于减少手动操作,提高工作效率。
- 持续集成与持续部署(CI/CD):MLflow支持持续集成和持续部署流程,使得机器学习模型的迭代和更新更加高效和快速。
综上所述,MLflow在机器学习项目中发挥着至关重要的作用,它提高了实验的可复现性、简化了项目打包和部署流程、优化了模型管理和版本控制、促进了团队协作与自动化工作流的实现。
二、安装使用
1.安装
pip install mlflow
启动后打开网页UI:
启动:mlflow server --host 127.0.0.1 --port 8080
访问http://<host>:<port>
一般是http://localhost:8080/
2.使用
2.1新建文件,运行启动
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
# 第一部分:数据集建模
# 加载并准备用于建模的 Iris 数据集。
# 训练逻辑回归模型并评估其性能。
# 准备模型超参数并计算日志记录指标。
# 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)
# 第二部分:关联
# 如果使用的是 Databricks 未提供的托管 MLflow 跟踪服务器,或者运行本地跟踪服务器,请确保使用以下命令设置跟踪服务器的 URI:
mlflow.set_tracking_uri(uri="http://localhost:8080/")
# Create a new MLflow Experiment
mlflow.set_experiment("MLflow Quickstart")
# 第三部分:启动
# 启动 MLflow 运行上下文以启动新运行,我们将模型和元数据记录到该运行。
# 记录模型参数和性能指标。
# 标记运行以便于检索。
# 在记录(保存)模型时,在 MLflow 模型注册表中注册模型。
# 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",
)
# 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]
2.2 查看视图
2.3 UI介绍
执行后:
执行中:
运行详情:
运行详情:
查看生成的模型:
2.4 模型使用
下载模型,放入工程同级目录:
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(X_test)
print(predict_proba_res)
运行结果:
至此,入门结束!