使用 MLflow、Azure 和 Docker 进行模型管理
原文:
towardsdatascience.com/model-management-with-mlflow-azure-and-docker-2920b51a5bdd
在第一篇文章中,我们探讨了 Docker 强大的能力,可以将应用程序及其依赖打包成可移植的容器,确保在各种环境之间的一致性。
在这个基础上,本文介绍了MLflow,这是机器学习工作流程中实验跟踪和模型管理的重要工具。我们将演示如何在 Docker 容器中部署和使用 MLflow 以确保可移植性并避免与依赖相关的问题。容器化的 MLflow 服务器将部署在Azure上,以实现更好的可扩展性、远程访问,以及重要的是团队协作。
什么是 MLflow
MLflow 是一个开源平台,简化了机器学习生命周期的管理,从实验跟踪到模型部署。它提供了一个稳定的框架来记录实验、管理代码和跟踪模型版本,确保您的团队工作流程可重复且井然有序。
MLflow 可以集成到机器学习管道的各个阶段。它提供四个主要组件:
-
MLflow 跟踪:这是最广泛使用的功能,允许您记录和查询实验。它跟踪有用的细节,如代码版本、数据集、配置、超参数、评估指标和结果。您可以通过用户友好的 Web 界面访问这些信息。
-
MLflow 项目:一种打包格式,使得您的代码可以在不同平台上可重复使用。MLflow 项目与版本控制系统如 Git 集成,使得跟踪和管理依赖变得容易。
-
MLflow 模型:此功能标准化了您打包机器学习模型的方式。它确保模型可以在不同环境中轻松部署而不会出现兼容性问题。
-
MLflow 模型注册表:一个集中式模型存储库,管理您模型的整个生命周期,包括版本控制、审批工作流程和部署过程。
在本文中,我们将重点关注MLflow 跟踪,这是允许数据科学家高效跟踪实验的核心功能。
MLflow 跟踪的全局架构
MLflow 跟踪提供了一个系统来记录和管理与您的机器学习实验相关的所有关键数据。以下是架构的工作方式:
MLflow 跟踪服务器:
这是核心组件。它是一个基于 Web 的服务,记录您的实验并通过用户友好的界面使它们可访问。您可以通过 URL 访问此界面以从任何地方跟踪实验。每次您运行实验(例如,训练模型)时,服务器都会记录:
-
代码:脚本或代码的版本。
-
超参数:训练参数,如学习率、批量大小等。
-
指标:如准确率、损失和精确度等性能指标。
-
结果:如模型文件或预测结果等输出。
我们将使用 Azure WebApp 来部署此服务器。
后端存储(数据库):
元数据(配置、参数、指标和日志)存储在后端数据库中。这是系统的“大脑”,有助于保持所有实验的结构化历史记录。您可以轻松查询、比较和分析过去的运行。我们将使用 Azure SQL 数据库。
工件存储:
工件存储是保存您实验中生成的文件的文件夹。我们将使用 Azure Blob 存储 来实现这一点。工件包括:
-
模型:训练好的模型。
-
图表:训练过程中创建的图表或图表。
-
数据文件:运行过程中生成的额外输出文件。
总结来说,在我们的案例中,我们将使用 Azure SQL 数据库 作为后端存储,Azure Blob 存储 作为工件存储,并通过 Azure 容器实例 和 Azure WebApp 来部署 MLflow 跟踪服务器,以确保可扩展性和易于管理。
通过实践掌握技能
您可以克隆此 文件夹 来找到本教程所需的全部脚本。
第 1 步:创建一个 Dockerfile
要托管 MLflow 服务器,我们首先使用 Dockerfile 创建一个 Docker 容器。以下是一个示例配置:
# Use Miniconda as the base image
FROM continuumio/miniconda3
# Set environment variables
ENV DEBIAN_FRONTEND=noninteractive
# Install necessary packages
RUN apt-get update -y &&
apt-get install -y --no-install-recommends curl apt-transport-https gnupg2 unixodbc-dev
# Add Microsoft SQL Server ODBC Driver 18 repository and install
RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - &&
curl https://packages.microsoft.com/config/debian/11/prod.list > /etc/apt/sources.list.d/mssql-release.list &&
apt-get update &&
ACCEPT_EULA=Y apt-get install -y msodbcsql18 mssql-tools18
# Add mssql-tools to PATH
RUN echo 'export PATH="$PATH:/opt/mssql-tools18/bin"' >> ~/.bash_profile &&
echo 'export PATH="$PATH:/opt/mssql-tools18/bin"' >> ~/.bashrc
# define default server env variables
ENV MLFLOW_SERVER_HOST 0.0.0.0
ENV MLFLOW_SERVER_PORT 5000
ENV MLFLOW_SERVER_WORKERS 1
# Set the working directory
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . /app
# Install Python dependencies specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
# Make sure the launch.sh script is executable
RUN chmod +x /app/launch.sh
# Expose port 5000 for MLflow
EXPOSE 5000
# Set the entrypoint to run the launch.sh script
ENTRYPOINT ["/app/launch.sh"]
此 Dockerfile 创建了一个运行 MLflow 服务器的容器。它安装了必要的工具,包括 Microsoft SQL Server ODBC 驱动程序,设置了环境,并安装了 Python 依赖项。然后,它将应用文件夹中的文件复制到容器中,暴露端口 5000(对于 MlFlow 是强制性的),并运行 launch.sh 脚本来启动 MLflow 服务器。
launch.sh 文件中只包含启动 mlflow 服务器的命令。
第 2 步:在本地构建和运行 Docker 容器
- 在包含您的 Dockerfile 的同一目录中构建 Docker 镜像:
docker build . -t mlflowserver
# if your are on mac, use :
# docker build - platform=linux/amd64 -t mlflowserver:latest .
运行 Docker 容器:
docker run -it -p 5000:5000 mlflowserver
运行这些命令后,MLflow 服务器将在本地启动,您可以通过导航到 http://localhost:5000 来访问 MLflow UI。这确认了服务器已成功部署在您的本地机器上。然而,在这个阶段,虽然您可以记录实验到 MLflow,但由于尚未配置,结果、工件或元数据都不会保存在 SQL 数据库或工件存储中。此外,URL 仅在本地可访问,这意味着您的数据科学团队无法远程访问它。
作者
第 3 步:设置 Azure 资源
首先创建一个 Azure 账户,并从 Azure 门户获取您的 订阅 ID。
要部署您的 MLflow 服务器并使其对您的团队可访问,请按照以下简化步骤操作:
-
克隆存储库:克隆此文件夹到您的本地机器。
-
运行部署脚本:以 shell 脚本的形式执行
deploy.sh脚本。在运行之前,请确保更新脚本中的 Subscription ID 变量。
虽然 Azure 提供了图形界面来设置资源,但本指南通过使用deploy.sh脚本来自动化整个过程,从而简化了流程。
下面是deploy.sh脚本逐步操作的分解:
1.登录并设置订阅:首先,登录到您的 Azure 账户,并设置所有资源将部署的正确订阅(从 Azure 门户检索订阅 ID)。
az login az account set --subscription $SUBSCRIPTION_ID
2.创建资源组:创建一个资源组来组织您为 MLflow 部署的所有资源。
az group create --name $RG_NAME --location <location>
3.设置 Azure SQL 数据库:创建一个 Azure SQL 服务器和一个 SQL 数据库,MLflow 将在这里存储所有实验元数据。
az sql server create
--name $SQL_SERVER_NAME
--resource-group $RG_NAME
--location $RG_LOCATION
--admin-user $SQL_ADMIN_USER
--admin-password $SQL_ADMIN_PASSWORD
az sql db create
--resource-group $RG_NAME
--server $SQL_SERVER_NAME
--name $SQL_DATABASE_NAME
--service-objective S0
4.配置 SQL 服务器防火墙:通过创建防火墙规则允许其他 Azure 服务访问 SQL 服务器。
az sql server firewall-rule create
--resource-group $RG_NAME
--server $SQL_SERVER_NAME
--name AllowAllAzureIPs
--start-ip-address 0.0.0.0
--end-ip-address 0.0.0.0
5.创建 Azure 存储账户:设置一个 Azure 存储 账户和一个 Blob 容器来存储工件(例如,模型、实验结果)。
az storage account create
--resource-group $RG_NAME
--location $RG_LOCATION
--name $STORAGE_ACCOUNT_NAME
--sku Standard_LRS
az storage container create
--name $STORAGE_CONTAINER_NAME
--account-name $STORAGE_ACCOUNT_NAME
6.创建 Azure 容器注册库(ACR):创建一个 Azure 容器注册库(ACR)来存储您的 MLflow 服务器的 Docker 镜像。
az acr create
--name $ACR_NAME
--resource-group $RG_NAME
--sku Basic
--admin-enabled true
7.构建并推送 Docker 镜像到 ACR:构建 MLflow 服务器的 Docker 镜像并将其推送到 Azure 容器注册库。为此,您需要首先检索 ACR 用户名和密码,并登录到 ACR。
export ACR_USERNAME=$(az acr credential show --name $ACR_NAME --query "username" --output tsv)
export ACR_PASSWORD=$(az acr credential show --name $ACR_NAME --query "passwords[0].value" --output tsv)
docker login $ACR_NAME.azurecr.io
--username "$ACR_USERNAME"
--password "$ACR_PASSWORD"
# Push the images
docker tag $DOCKER_IMAGE_NAME $ACR_NAME.azurecr.io/$DOCKER_IMAGE_NAME:$DOCKER_IMAGE_TAG
docker push $ACR_NAME.azurecr.io/$DOCKER_IMAGE_NAME:$DOCKER_IMAGE_TAG
8.创建应用服务计划:设置一个应用服务计划来在 Azure 上托管您的 MLflow 服务器。
az appservice plan create
--name $ASP_NAME
--resource-group $RG_NAME
--sku B1
--is-linux
--location $RG_LOCATION
9.使用 MLflow 容器部署 Web 应用:创建一个使用 ACR 中的 Docker 镜像的Web 应用来部署 MLflow 服务器。
az webapp create
--resource-group $RG_NAME
--plan $ASP_NAME
--name $WEB_APP_NAME
--deployment-container-image-name $ACR_NAME.azurecr.io/$DOCKER_IMAGE_NAME:$DOCKER_IMAGE_TAG
10.配置 Web 应用以使用容器注册库:设置您的 Web 应用以从 ACR 拉取 MLflow Docker 镜像,并配置环境变量。
az webapp config container set
--name $WEB_APP_NAME
--resource-group $RG_NAME
--docker-custom-image-name $ACR_NAME.azurecr.io/$DOCKER_IMAGE_NAME:$DOCKER_IMAGE_TAG
--docker-registry-server-url https://$ACR_NAME.azurecr.io
--docker-registry-server-user $ACR_USERNAME
--docker-registry-server-password $ACR_PASSWORD
--enable-app-service-storage true
az webapp config appsettings set
--resource-group $RG_NAME
--name $WEB_APP_NAME
--settings WEBSITES_PORT=$MLFLOW_PORT
az webapp log config
--name $WEB_APP_NAME
--resource-group $RG_NAME
--docker-container-logging filesystem
11.设置 Web 应用环境变量:为 MLflow 设置必要的环境变量,例如存储访问、SQL 后端和端口设置。
echo "Retrive artifact, access key, connection string"
export STORAGE_ACCESS_KEY=$(az storage account keys list --resource-group $RG_NAME --account-name $STORAGE_ACCOUNT_NAME --query "[0].value" --output tsv)
export STORAGE_CONNECTION_STRING=`az storage account show-connection-string --resource-group $RG_NAME --name $STORAGE_ACCOUNT_NAME --output tsv`
export STORAGE_ARTIFACT_ROOT="https://$STORAGE_ACCOUNT_NAME.blob.core.windows.net/$STORAGE_CONTAINER_NAME"
#Setting environment variables for artifacts and database
az webapp config appsettings set
--resource-group $RG_NAME
--name $WEB_APP_NAME
--settings AZURE_STORAGE_CONNECTION_STRING=$STORAGE_CONNECTION_STRING
az webapp config appsettings set
--resource-group $RG_NAME
--name $WEB_APP_NAME
--settings BACKEND_STORE_URI=$BACKEND_STORE_URI
az webapp config appsettings set
--resource-group $RG_NAME
--name $WEB_APP_NAME
--settings MLFLOW_SERVER_DEFAULT_ARTIFACT_ROOT=$STORAGE_ARTIFACT_ROOT
#Setting environment variables for the general context
az webapp config appsettings set
--resource-group $RG_NAME
--name $WEB_APP_NAME
--settings MLFLOW_SERVER_PORT=$MLFLOW_PORT
az webapp config appsettings set
--resource-group $RG_NAME
--name $WEB_APP_NAME
--settings MLFLOW_SERVER_HOST=$MLFLOW_HOST
az webapp config appsettings set
--resource-group $RG_NAME
--name $WEB_APP_NAME
--settings MLFLOW_SERVER_FILE_STORE=$MLFLOW_FILESTORE
az webapp config appsettings set
--resource-group $RG_NAME
--name $WEB_APP_NAME
--settings MLFLOW_SERVER_WORKERS=$MLFLOW_WORKERS
一旦deploy.sh脚本完成,您可以通过检查 Azure 门户来验证是否已创建所有 Azure 服务。
作者
前往应用服务部分以检索您的 MLflow Web 应用的 URL。
作者
您的 MLflow 跟踪 URL 现在应该是活跃的,并准备好接收来自您的数据科学团队的实验。
作者
第 3 步:使用 Scikit-Learn 和 MLflow 记录实验
这里有一个 Python 脚本,演示了如何使用 MLflow 和简单的 scikit-learn 模型(如逻辑回归)记录实验。请确保你更新脚本中的 MLflow 跟踪 URI:
import os
import mlflow
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import joblib
# Load Iris dataset
iris = load_iris()
# Split dataset into X features and Target variable
X = pd.DataFrame(data = iris["data"], columns= iris["feature_names"])
y = pd.Series(data = iris["target"], name="target")
# Split our training set and our test set
X_train, X_test, y_train, y_test = train_test_split(X, y)
# Set your variables for your environment
EXPERIMENT_NAME="experiment1"
# Set tracking URI to your Heroku application
mlflow.set_tracking_uri("set your mlflow tracking URI")
# mlflow.set_tracking_uri("http://localhost:5000")
# Set experiment's info
mlflow.set_experiment(EXPERIMENT_NAME)
# Get our experiment info
experiment = mlflow.get_experiment_by_name(EXPERIMENT_NAME)
# Call mlflow autolog
mlflow.sklearn.autolog()
with open("test.txt", "w") as f:
f.write("hello world!")
with mlflow.start_run(experiment_id = experiment.experiment_id):
# Specified Parameters
c = 0.1
# Instanciate and fit the model
lr = LogisticRegression(C=c)
lr.fit(X_train.values, y_train.values)
# Store metrics
predicted_qualities = lr.predict(X_test.values)
accuracy = lr.score(X_test.values, y_test.values)
# Print results
print("LogisticRegression model")
print("Accuracy: {}".format(accuracy))
# Log Metric
mlflow.log_metric("Accuracy", accuracy)
# Log Param
mlflow.log_param("C", c)
mlflow.log_artifact('test.txt')
通过运行此脚本,你应该能够将你的模型、指标和工件记录到 MLflow 中。工件将存储在 Azure Blob 存储中,而元数据将保存在 Azure SQL 数据库中。
第 4 步:检查结果
1 检查 MLflow 跟踪:访问你的 MLflow 跟踪 URL 以找到你的实验、运行名称以及所有相关的指标和模型参数
作者提供
作者提供
检查 MLflow 工件:在 MLflow UI 中访问工件,并验证它们在 Azure Blob 存储中的存在
作者提供
作者提供
现在,你和你的团队可以向 MLflow 提交实验,通过跟踪 URI 跟踪它们,并从 Azure 存储检索模型信息或文件。在下一个教程中,我们将探讨如何创建一个 API 来读取存储在 Azure 存储中的模型。
结论
你已成功设置 MLflow 与 Azure 配合进行跟踪和管理你的机器学习实验。请注意,根据你的计算机和操作系统,你可能会遇到与 Docker、MLflow 或 Azure 服务相关的一些问题。如果你遇到麻烦,请不要犹豫,寻求帮助。
接下来,我们将探讨如何使用存储在 Azure Blob 存储中的 MLflow 模型来创建一个 API,完成自动化工作流程。
感谢阅读!
***注意:*本文的部分内容最初是用法语编写的,并在 ChatGPT 的帮助下翻译成英语。
更多推荐

所有评论(0)