英文链接:https://mlflow.org/docs/latest/tutorial.html

本文链接:https://www.cnblogs.com/CheeseZH/p/11943280.html

这篇教程展示了如何:

  1. 训练一个线性回归模型
  2. 将训练代码打包成一个可复用可复现的模型格式
  3. 将模型部署成一个简单的HTTP服务用于进行预测

这篇教程使用的数据来自UCI的红酒质量数据集,主要用于根据红酒的PH值,酸度,残糖量等指标来评估红酒的质量。

我们会用到什么?

  • 如果使用的是MacOS,官方推荐使用python3环境
  • 安装MLflow和scikit-learn,推荐两种安装方式:
    • 安装MLflow及其依赖:pip install mlflow[extras]
    • 分别安装MLflow(pip install mlflow)和scikit-learn(pip install scikit-learn)
  • 安装conda

训练模型

我们要训练的线性回归模型包含两个超参数:alphal1_ratio

我们使用下边的train.py代码进行训练

# The data set used in this example is from http://archive.ics.uci.edu/ml/datasets/Wine+Quality
# P. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis.
# Modeling wine preferences by data mining from physicochemical properties. In Decision Support Systems, Elsevier, 47(4):547-553, 2009. import os
import warnings
import sys import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.linear_model import ElasticNet import mlflow
import mlflow.sklearn import logging
logging.basicConfig(level=logging.WARN)
logger = logging.getLogger(__name__) def eval_metrics(actual, pred):
rmse = np.sqrt(mean_squared_error(actual, pred))
mae = mean_absolute_error(actual, pred)
r2 = r2_score(actual, pred)
return rmse, mae, r2 if __name__ == "__main__":
warnings.filterwarnings("ignore")
np.random.seed(40) # Read the wine-quality csv file from the URL
csv_url =\
'http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv'
try:
data = pd.read_csv(csv_url, sep=';')
except Exception as e:
logger.exception(
"Unable to download training & test CSV, check your internet connection. Error: %s", e) # Split the data into training and test sets. (0.75, 0.25) split.
train, test = train_test_split(data) # The predicted column is "quality" which is a scalar from [3, 9]
train_x = train.drop(["quality"], axis=1)
test_x = test.drop(["quality"], axis=1)
train_y = train[["quality"]]
test_y = test[["quality"]] alpha = float(sys.argv[1]) if len(sys.argv) > 1 else 0.5
l1_ratio = float(sys.argv[2]) if len(sys.argv) > 2 else 0.5 with mlflow.start_run():
lr = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, random_state=42)
lr.fit(train_x, train_y) predicted_qualities = lr.predict(test_x) (rmse, mae, r2) = eval_metrics(test_y, predicted_qualities) print("Elasticnet model (alpha=%f, l1_ratio=%f):" % (alpha, l1_ratio))
print(" RMSE: %s" % rmse)
print(" MAE: %s" % mae)
print(" R2: %s" % r2) mlflow.log_param("alpha", alpha)
mlflow.log_param("l1_ratio", l1_ratio)
mlflow.log_metric("rmse", rmse)
mlflow.log_metric("r2", r2)
mlflow.log_metric("mae", mae) mlflow.sklearn.log_model(lr, "model")

这个例子用pandas,numpy,sklearn的API构建了一个简单的机器学习模型。通过MLflow tracking APIs来记录每次训练的信息,比如模型超参数和模型的评价指标。这个例子还将模型进行了序列化以便后续部署。

我们用不同的超参数训练几次模型

python train.py 0.5 0.5
python train.py 0.4 0.4
python train.py 0.6 0.6

每次运行完训练脚本,MLflow都会将信息保存在目录mlruns中。

对比模型

mlruns目录的上级目录中运行下边的命令:

mlflow ui

然后就可以通过http://localhost:5000来查看每个版本的模型了。

MLflow系列1:MLflow入门教程(Python)-LMLPHP

我们可以通过搜索功能快速筛选感兴趣的模型,比如搜索条件设置为metrics.rmse<0.8可以将rmse小于0.8的模型找出来,如果更复杂的搜索条件,可以下载CSV文件并用其他软件进行分析。

打包模型

我们已经写好了训练代码,可以将其打包提供给其他的数据科学家来复用,或者可以进行远程训练。

我们根据MLflow Projects的惯例来指定代码的依赖和代码的入口。比如创建一个sklearn_elasticnet_wine目录,在这个目录下创建一个MLproject文件来指定项目的conda依赖和包含两个参数alpha/l1_ratio的入口文件。

# sklearn_elasticnet_wine/MLproject

name: tutorial

conda_env: conda.yaml

entry_points:
main:
parameters:
alpha: float
l1_ratio: {type: float, default: 0.1}
command: "python train.py {alpha} {l1_ratio}"

conda.yaml文件列举了所有依赖:

# sklearn_elasticnet_wine/conda.yaml

name: tutorial
channels:
- defaults
dependencies:
- numpy=1.14.3
- pandas=0.22.0
- scikit-learn=0.19.1
- pip:
- mlflow

通过执行mlflow run examples/sklearn_elasticnet_wine -P alpha=0.42可以运行这个项目,MLflow会根据conda.yaml的配置在指定的conda环境中训练模型。

如果代码仓库的根目录有MLproject文件,也可以直接通过Github来运行,比如代码仓库:https://github.com/mlflow/mlflow-example。我们可以执行这个命令mlflow run git@github.com:mlflow/mlflow-example.git -P alpha=0.42来训练模型。

部署模型

我们通过MLflow Models来部署模型。一个MLflow Model是一种打包机器学习模型的标准格式,可以被用于多种下游工具,比如实时推理的REST API或者批量推理的Apache Spark。

在训练代码中,这行代码用于保存模型(原文称为artifact,暂且翻译成模型产品吧):

mlflow.sklearn.log_model(lr, "model")

我们可以在UI中通过点击Date链接来查看每次训练的模型产品,例如:

MLflow系列1:MLflow入门教程(Python)-LMLPHP

在底部,我们可以看到通过调用mlflow.sklearn.log_model产生了两个文件,位于类似目录/Users/mlflow/mlflow-prototype/mlruns/0/7c1a0d5c42844dcdb8f5191146925174/artifacts/modelMLmodel元数据文件是告诉MLflow如何加载模型。model.pkl文件是训练好的序列化的线性回归模型。

运行下边的命令,可以将模型部署成本地REST服务(要确保训练模型和部署模型所用的python版本一致,否则会报错):

# 需要替换成你自己的目录
mlflow models serve -m /Users/mlflow/mlflow-prototype/mlruns/0/7c1a0d5c42844dcdb8f5191146925174/artifacts/model -p 1234

部署好服务之后,可以通过curl命令发送json序列化的pandas DataFrame来测试下。模型服务器接受的数据格式可以参考MLflow deployment tools documentation.

curl -X POST -H "Content-Type:application/json; format=pandas-split" \
--data '{"columns":["alcohol", "chlorides", "citric acid", "density", "fixed acidity", "free sulfur dioxide", "pH", "residual sugar", "sulphates", "total sulfur dioxide", "volatile acidity"],"data":[[12.8, 0.029, 0.48, 0.98, 6.2, 29, 3.33, 1.2, 0.39, 75, 0.66]]}' \
http://127.0.0.1:1234/invocations

服务器会返回类似输出:

[6.379428821398614]
05-27 09:50