创建容器化机器学习模型

数据科学家创建机器学习模型后,必须将其部署到生产中。 要在不同的基础架构上运行它,使用容器并通过 REST API 公开模型是部署机器学习模型的常用方法。 本文演示了如何推出 TensorFlow 机器学习模型,带有由 REST API 提供的 连接 在 Podman 的容器中。

准备

首先,使用以下命令安装 Podman:

sudo dnf -y install podman

接下来,为容器创建一个新文件夹并切换到该目录。

mkdir deployment_container && cd deployment_container

用于 TensorFlow 模型的 REST API

下一步是为机器学习模型创建 REST-API。 这 github仓库 包含一个预训练的模型,以及已经为使 REST API 工作而配置的设置。

使用以下命令将其克隆到 deployment_container 目录中:

git clone https://github.com/svenboesiger/titanic_tf_ml_model.git

预测.py & ml_model/

预测.py 文件允许进行 TensorFlow 预测,而 20x20x20 神经网络的权重位于文件夹中 ml_model/.

招摇的.yaml

swagger.yaml 文件定义了 Connexion 库的 API,使用 招摇规范. 此文件包含配置服务器以提供输入参数验证、输出响应数据验证、URL 端点定义所需的所有信息。

作为奖励,Connexion 还将为您提供一个简单但有用的单页 Web 应用程序,该应用程序演示了将 API 与 JavaScript 结合使用并使用它更新 DOM。

swagger: "2.0"
info:
  description: This is the swagger file that goes with our server code
  version: "1.0.0"
  title: Tensorflow Podman Article
consumes:
  - "application/json"
produces:
  - "application/json"


basePath: "/"

paths:
  /survival_probability:
    post:
      operationId: "prediction.post"
      tags:
        - "Prediction"
      summary: "The prediction data structure provided by the server application"
      description: "Retrieve the chance of surviving the titanic disaster"
      parameters:
        - in: body
          name: passenger
          required: true
          schema:
            $ref: '#/definitions/PredictionPost'
      responses:
        '201':
          description: 'Survival probability of an individual Titanic passenger'

definitions:
  PredictionPost:
    type: object

server.py & requirements.txt

服务器.py 定义启动 Connexion 服务器的入口点。

import connexion

app = connexion.App(__name__, specification_dir="./")

app.add_api('swagger.yaml')

if __name__ == '__main__':
    app.run(debug=True)

要求.txt 定义了我们运行程序所需的 python 要求。

connexion
tensorflow
pandas

集装箱化!

为了让 Podman 能够构建镜像,请在 部署容器 在上述准备步骤中创建的目录:

FROM fedora:28
 
# File Author / Maintainer
MAINTAINER Sven Boesiger <[email protected]>
 
# Update the sources
RUN dnf -y update --refresh
 
# Install additional dependencies
RUN dnf -y install libstdc++
 
RUN dnf -y autoremove
 
# Copy the application folder inside the container
ADD /titanic_tf_ml_model /titanic_tf_ml_model
 
# Get pip to download and install requirements:
RUN pip3 install -r /titanic_tf_ml_model/requirements.txt
 
# Expose ports
EXPOSE 5000
 
# Set the default directory where CMD will execute
WORKDIR /titanic_tf_ml_model
 
# Set the default command to execute   
# when creating a new container
CMD python3 server.py

接下来,使用以下命令构建容器映像:

podman build -t ml_deployment .

运行容器

容器镜像构建完成并准备就绪后,您可以使用以下命令在本地运行它:

podman run -p 5000:5000 ml_deployment

导航 https://0.0.0.0:5000/ui 在 Web 浏览器中访问 Swagger/Connexion UI 并测试模型:

当然,您现在也可以通过 REST-API 使用您的应用程序访问模型。