简单到老板也可以亲自部署这篇博文演示了如何通过Docker和Kubernetes,用Keras部署深度学习模型,并且通过Flask提供REST API服务。

这个模型并不是强壮到可供生产的模型,而是给Kubernetes新手一个尝试的机会。我在Google Cloud上部署了这个模型,而且工作的很好。另外用户可以用同样的步骤重现以上功能。如果用户担心成本,Google提供了大量免费机会,这个演示基本没有花钱。

为什么用Kubernetes来做机器学习和数据科学Kubernetes以及Cloud Native,正在席卷整个世界,我们已经感受到了。我们正处在一个由AI/Big Data/Cloud驱动的技术风暴中心,Kubernetes也正在加入这个中心。

但是如果从数据科学角度看并没有使用Kubernetes的特殊原因。但是从部署,扩展和管理REST API方面来看,Kubernetes正在实现简易化的特性。

步骤预览在Google Cloud上创建用户

使用Keras/Flask/Docker搭建一个REST API的机器学习模型服务

用Kubernetes部署上述模型

enjoy it

步骤一:在Google Cloud上创建用户我在Google Compute Engine上创建了一个对外提供服务的容器化深度学习模型,当然Google平台并不是必须的,只要能够安装Docker,随便选择平台模式。

进入Google云平台,点击左侧屏幕选择Compute Engine,启动Google Cloud VM。然后选择“Create Instance”,可以看到已经运行的实例。

下一步选择计算资源。默认设置就足够,因为只是演示,我选择了4vCPUs和15G内存。

选择操作系统和磁盘大小。我选择了CentOS 7,100G硬盘。建议磁盘大于10G,因为每个Docker容器有1G大小。

最后一步是配置允许HTTP/S工作的防火墙策略。建议选择全部透明,以便减少麻烦。

选择“Create”,一切进展顺利。

步骤二:用Keras创建深度学习模型SSH登录到虚机开始建立模型。最简单方式就是点击虚机下方的SSH图标,会在浏览器中打开一个终端。

1、删除预装Docker

sudo yum remove docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-selinux docker-engine-selinux docker-engine

2、安装最新Docker版本

sudo yum install -y yum-utils device-mapper-persistent-data lvm2

sudo yum-config-manager — add-repo https://download.docker.com/linux/centos/docker-ce.repo

sudo yum install docker-ce

3、启动容器运行测试脚本

sudo systemctl start docker

sudo docker run hello-world

以下是正确输出:

Hello from Docker!

This message shows that your installation appears to be working correctly.To generate this message, Docker took the following steps: 1. The Docker client contacted the Docker daemon. 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.    (amd64) 3. The Docker daemon created a new container from that image which runs the    executable that produces the output you are currently reading. 4. The Docker daemon streamed that output to the Docker client, which sent it    to your terminal

4、创建深度学习模型

这里会借用Adrian Rosebrock的一个脚本,他提供了使用Keras的深度学习模型并通过Flask提供服务的教程,可以从这里访问。

这个模型可以直接执行。但是我修改了两个配置信息:

首先,改变了容器配置,默认flask使用127.0.0....作为默认服务地址,这会在容器内部运行时出现问题。我将它修改成0.0.0.0,这样就可以实现对外和对内都可以工作的IP地址。

第二是关于Tensorflow的配置,可以从GitHub中找到这个问题描述。

global graph

graph = tf.get_default_graph()

...

with graph.as_default():

preds = model.predict(image)

运行脚本,首先创建专用目录:

mkdir keras-app

cd keras-app

创建app.py文件:

vim app.py

# USAGE

Start the server:

python app.py

Submit a request via cURL:

curl -X POST -F image=@dog.jpg 'http://localhost:5000/predict'

import the necessary packagesfrom keras.applications import ResNet50

from keras.preprocessing.image import img_to_array

from keras.applications import imagenet_utils

from PIL import Image

import numpy as np

import flask

import io

import tensorflow as tf

initialize our Flask application and the Keras modelapp = flask.Flask(__name__)

model = None

def load_model():

# load the pre-trained Keras model (here we are using a model

# pre-trained on ImageNet and provided by Keras, but you can

# substitute in your own networks just as easily)

global model

model = ResNet50(weights="imagenet")

global graph

graph = tf.get_default_graph()

def prepare_image(image, target):

# if the image mode is not RGB, convert it

if image.mode != "RGB":

image = image.convert("RGB")

# resize the input image and preprocess it

image = image.resize(target)

image = img_to_array(image)

image = np.expand_dims(image, axis=0)

image = imagenet_utils.preprocess_input(image)

# return the processed image

return image

@app.route("/predict", methods=["POST"])

def predict():

# initialize the data dictionary that will be returned from the

# view

data = {"success": False}

# ensure an image was properly uploaded to our endpoint

if flask.request.method == "POST":

if flask.request.files.get("image"):

# read the image in PIL format

image = flask.request.files["image"].read()

image = Image.open(io.BytesIO(image))

# preprocess the image and prepare it for classification

image = prepare_image(image, target=(224, 224))

# classify the input image and then initialize the list

# of predictions to return to the client

with graph.as_default():

preds = model.predict(image)

results = imagenet_utils.decode_predictions(preds)

data["predictions"] = []

# loop over the results and add them to the list of

# returned predictions

for (imagenetID, label, prob) in results[0]:

r = {"label": label, "probability": float(prob)}

data["predictions"].append(r)

# indicate that the request was a success

data["success"] = True

# return the data dictionary as a JSON response

return flask.jsonify(data)

if this is the main thread of execution first load the model and

then start the serverif __name__ == "__main__":

print(("* Loading Keras model and Flask starting server..."

"please wait until server has fully started"))

load_model()

app.run(host='0.0.0.0')

5、创建requirements.txt文件

为了在容器内运行代码,需要创建requirements.txt文件,其中包括需要运行的包,例如keras、flask、一起其它相关包。这样无论在哪里运行代码,依赖包都保持一致。

keras

tensorflow

flask

gevent

pillow

requests

6、创建Dockerfile

FROM python:3.6

WORKDIR /app

COPY requirements.txt /app

RUN pip install -r ./requirements.txt

COPY app.py /app

CMD ["python", "app.py"]~

首先让容器自行下载Python 3安装image,然后让Python调用pip安装requirements.txt中的依赖包,最后运行python app.py。

7、创建容器

sudo docker build -t keras-app:latest .

在keras-app目录下创建容器,后台开始安装Python 3 image等在步骤6中定义的操作。

8、运行容器

sudo docker run -d -p 5000:5000 keras-app

用sudo docker ps -a检查容器状态,应该看到如下输出:

[gustafcavanaugh@instance-3 ~]$ sudo docker ps -a

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                    PORTS                    NAMES

d82f65802166        keras-app           "python app.py"     About an hour ago   Up About an hour          0.0.0.0:5000->5000/tcp   nervous_northcutt

9、测试模型

现在可以测试此模型。用狗的照片作为输入,可以返回狗的品种。在Adrian的示例中都有详细代码和图片,我们也使用它们,并保存自工作目录下,命名为dog.jpg。

执行命令:

curl -X POST -F image=@dog.jpg 'http://localhost:5000/predict'

应该得到如下输出:

{"predictions":[{"label":"beagle","probability":0.987775444984436},{"label":"pot","probability":0.0020967808086425066},{"label":"Cardigan","probability":0.001351703773252666},{"label":"Walker_hound","probability":0.0012711131712421775},{"label":"Brittany_spaniel","probability":0.0010085132671520114}],"success":true}

可以看到此模型成功将狗归类为比格犬。下一步,我们用Kubernetes部署容器模型。

第三步:用Kubernetes部署模型1、创建Docker Hub账号

第一步需要在Docker hub上传模型,以便使用Kubernetes集中管理。

2、登录到Docker Hub

sudo docker login, 登录到Docker Hub,应该看到如下输出:

Login Succeeded

3、给容器打标签

给模型容器命名,上传前先给它打标签。

sudo docker images,应该得到容器的id,输出如下:

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE keras-app           latest              ddb507b8a017        About an hour ago   1.61GB

打标签命令如下:

#Format

sudo docker tag  /

My Exact Command - Make Sure To Use Your Inputssudo docker tag ddb507b8a017 gcav66/keras-app

4、将模型容器上传到Docker Hub

运行命令如下:

#Format

sudo docker push /

My exact commandsudo docker push gcav66/keras-app

5、创建Kubernetes集群

在Google Cloud Home界面,选择Kubernetes Engine。

创建新集群:

选择集群内节点资源,因为要启动三个节点(每个节点4vCPU和15G内存),至少需要12vCPU和45G内存。

连接集群,Google’s Kubernetes自动会在VM上安装Kubernetes。

在Kubernetes中运行容器:

kubectl run keras-app --image=gcav66/keras-app --port 5000

确认是否Pod正确运行kubectl get pods,输出如下:

gustafcavanaugh@cloudshell:~ (basic-web-app-test)$ kubectl get pods

NAME                         READY     STATUS    RESTARTS   AGE

keras-app-79568b5f57-5qxqk   1/1       Running   0          1m

为了安全起见,将服务端口暴露与80端口:

kubectl expose deployment keras-app --type=LoadBalancer --port 80 --target-port 5000

确认服务正常启动:kubectl get service,正常输出如下:

gustafcavanaugh@cloudshell:~ (basic-web-app-test)$ kubectl get service

NAME         TYPE           CLUSTER-IP     EXTERNAL-IP     PORT(S)        AGE

keras-app    LoadBalancer   10.11.250.71   35.225.226.94   80:30271/TCP   4m

kubernetes   ClusterIP      10.11.240.1              443/TCP        18m

提取cluster-IP,并将其合并于服务提交命令:curl -X POST -F image=@dog.jpg 'http://<your service IP>/predict',得到正常输入如下:

$ curl -X POST -F image=@dog.jpg 'http://35.225.226.94/predict'

{"predictions":[{"label":"beagle","probability":0.987775444984436},{"label":"pot","probability":0.0020967808086425066},{"label":"Cardigan","probability":0.001351703773252666},{"label":"Walker_hound","probability":0.0012711131712421775},{"label":"Brittany_spaniel","probability":0.0010085132671520114}],"success":true}

第四步:总结本文提供了一个使用Keras和Flask提供REST API服务的深度学习模型,并把它集成到容器内部,上传到Docker Hub,并用Kubernetes部署,非常容易地实现了对外提供服务和访问。

现在,我们可以对这个项目进行很多改进。对于初学者,可以改变本地Python服务到更加强壮的gunicorn;可以横向扩展Kubernetes,实现服务扩容;也可以从头搭建一套Kubernetes环境。

python keras_用Python/Keras/Flask/Docker在Kubernetes上部署深度学习模型相关推荐

  1. 利用docker部署深度学习模型的一个最佳实践

    编程狗在线 自由的编程学习平台 前言 最近团队的模型部署上线终于全面开始用上docker了,这感觉,真香! 讲道理,docker是天然的微服务,确实是能敏捷高效的解决深度学习这一块的几个痛点. 部分神 ...

  2. 为什么将表格的method改为post后就无法工作_用Python将Keras深度学习模型部署为Web应用程序...

    构建一个很棒的机器学习项目是一回事,但归根结底,你希望其他人能够看到你的辛勤工作.当然,你可以将整个项目放在GitHub上,但是怎么让你的祖父母也看到呢?我们想要的是将深度学习模型部署为世界上任何人都 ...

  3. 怎么装python的keras库_matlab调用keras深度学习模型(环境搭建)

    matlab没有直接调用tensorflow模型的接口,但是有调用keras模型的接口,而keras又是tensorflow的高级封装版本,所以就研究一下这个--可以将model-based方法和le ...

  4. 【基于 docker 的 Flask 的深度学习模型部署】

    文章目录 1.前言 2.docker简介 3.基于Falsk的REST API实现 4.编写dockerfile 5.基于docker的模型部署 1.前言 模型部署一直是深度学习算法走向落地的重要的一 ...

  5. 【Flask和Docker部署Pytorch深度学习模型】

    文章目录 1.模型训练 2.Flask搭建模型 3.构建Docker镜像 4.Win 10安装Docker 4.1.修改下载默认源 4.2.修改镜像存放目录 4.3.镜像的创建 4.4.基础镜像 4. ...

  6. Flask和Docker部署Pytorch深度学习模型

    模型训练 预先训练深度学习模型,保存训练后的模型或参数,此处采用图像分类模型. Flask搭建模型 Flask是一个使用 Python 编写的轻量级Web应用框架,可通过$pip install fl ...

  7. C++调用Python文件,TensorFlow和PyTorch构建的深度学习模型,无法使用GPU的情况分析。

    C++调用Python深度学习模型,包含TensorFlow和PyTorch等构造的模型,然后使用GPU出现问题.包含C++调用Python函数,C++加载模型到GPU,GPU内存占用过大,计算完毕内 ...

  8. python打包exe之打包深度学习模型踩坑记录及其解决办法。

    在现实生活中,有时候我们写的程序需要发给小伙伴用,而小伙伴没有python,这时候我们需要将程序打包成exe文件发给小伙伴用. 今天讲下打包深度学习模型 打包一般要用到cmd命令行,要求cmd能执行p ...

  9. python网格搜索法_Python中基于网格搜索算法优化的深度学习模型分析糖尿病数据...

    介绍 在本教程中,我们将讨论一种非常强大的优化(或自动化)算法,即网格搜索算法.它最常用于机器学习模型中的超参数调整.我们将学习如何使用Python来实现它,以及如何将其应用到实际应用程序中,以了解它 ...

  10. 深度学习模型的准备和使用教程,LSTM用于锂电池SOH预测(第一节)(附Python的jypter源代码)

    本Python笔记本显示和分析了如何处理NASA获得的电池充电/放电数据集. 对于这个模型的训练阶段,需要安装Python 3.x以及以下库: Tensorflow 2.0 Numpy Pandas ...

最新文章

  1. python场景建立_Python创建一个街道地址表-问答-阿里云开发者社区-阿里云
  2. android studio无线真机调试------Android
  3. ubuntu MNN编译安装
  4. HDU - 5572 An Easy Physics Problem(几何-碰撞问题)
  5. 如何修改MFC的图标
  6. reddit_如何将多个子Reddit与多个Reddit合并
  7. mybatis学习(25):分页3 多参数传递(使用map)
  8. python抢票代码_GitHub标星超12K,抢票神器大更新,支持候补
  9. python中config命令_【Python】 配置解析ConfigParser 命令行参数解析optparser
  10. Linux 下几款程序内存泄漏检查工具
  11. python经典实例-终于明了python入门经典实例
  12. 这样的代码才是好代码
  13. shell脚本显示颜色的设置
  14. 阿里云张建锋:数字技术要服务好实体经济
  15. 【Vue.js】iconfont中unicode引用和unicode引用失败,无法显示icon
  16. graphpad 安装 hello world
  17. Eclipse学习笔记
  18. SQL Server2019安装步骤(超详细 附下载链接)
  19. 腾讯互娱AMS | 我的打包我做主——浅析前端构建
  20. 用心行走——《做最好的新教师》读后感3200字

热门文章

  1. nginx常见配置详解
  2. 375. 猜数字大小 II leetcode java
  3. 启动一个SpringBoot的maven项目
  4. postgresql 模式与用户,及跨库访问
  5. ORACLE lag,lead
  6. (转)在NGUI使用图片文字(数字、美术字)(直接可用于UILable)
  7. SqlDataReader.GetFloat出错,类型无法转换
  8. Spring转换编码utf-8方式
  9. gcc/g++/make/cmake/makefile/cmakelists的恩恩怨怨
  10. java (Eclipse)连接MySQL数据库