目录

task.py

data_utils.py

Dockerfile

下一步


  • 下载源 - 1.2 MB

在本系列文章中,我们将引导您完成将CI/CD应用于AI任务的过程。您最终会得到一个满足Google MLOps 成熟度模型2级要求的功能管道。我们假设您对Python、深度学习、Docker、DevOps和Flask有一定的了解。

在上一篇文章中,我们讨论了ML CI/CD管道中的单元测试步骤。在本节中,我们将构建模型API以支持预测服务。

下图显示了我们在项目过程中的位置。

代码文件的结构如下:

本文中的大部分代码与上一篇几乎相同,因此我们只看不同之处。

在此存储库中查找完整代码,因为下面显示的代码段是精简版本。

task.py

协调容器内程序执行的task.py文件如下所示:

import tensorflow as tf
from tensorflow.keras.models import load_model
import jsonpickle
import data_utils, email_notifications
import sys
import os
from google.cloud import storage
import datetime
import numpy as np
import jsonpickle
import cv2
from flask import flash,Flask,Response,request,jsonify
import threading
import requests
import time# IMPORTANT
# If you're running this container locally and you want to access the API via local browser, use http://172.17.0.2:5000/# Starting flask app
app = Flask(__name__)# general variables declaration
model_name = 'best_model.hdf5'
bucket_name = 'automatictrainingcicd-aiplatform'
global model@app.before_first_request
def before_first_request():def initialize_job():if len(tf.config.experimental.list_physical_devices('GPU')) > 0:tf.config.set_soft_device_placement(True)tf.debugging.set_log_device_placement(True)global model# Checking if there's any model saved at testing on GCSmodel_gcs = data_utils.previous_model(bucket_name,model_name)# If any model exists at prod, load it, test it on data and use it on the APIif model_gcs[0] == True:model_gcs = data_utils.load_model(bucket_name,model_name)if model_gcs[0] == True:try:model = load_model(model_name)except Exception as e:email_notifications.exception('Something went wrong trying to production model. Exception: '+str(e))sys.exit(1)else:email_notifications.exception('Something went wrong when trying to load production model. Exception: '+str(model_gcs[1]))sys.exit(1)if model_gcs[0] == False:email_notifications.send_update('There are no artifacts at model registry. Check GCP for more information.')sys.exit(1)if model_gcs[0] == None:email_notifications.exception('Something went wrong when trying to check if production model exists. Exception: '+model_gcs[1]+'. Aborting execution.')sys.exit(1)thread = threading.Thread(target=initialize_job)thread.start()@app.route('/init', methods=['GET','POST'])
def init():message = {'message': 'API initialized.'}response = jsonpickle.encode(message)return Response(response=response, status=200, mimetype="application/json")@app.route('/', methods=['POST'])
def index():if request.method=='POST':try:#Converting string that contains image to uint8image = np.fromstring(request.data,np.uint8)image = image.reshape((128,128,3))image = [image]image = np.array(image)image = image.astype(np.float16)result = model.predict(image)result = np.argmax(result)message = {'message': '{}'.format(str(result))}json_response = jsonify(message)return json_responseexcept Exception as e:message = {'message': 'Error'}json_response = jsonify(message)email_notifications.exception('Something went wrong when trying to make prediction via Production API. Exception: '+str(e)+'. Aborting execution.')return json_responseelse:message = {'message': 'Error. Please use this API in a proper manner.'}json_response = jsonify(message)return json_responsedef self_initialize():def initialization():global startedstarted = Falsewhile started == False:try:server_response = requests.get('http://127.0.0.1:5000/init')if server_response.status_code == 200:print('API has started successfully, quitting initialization job.')started = Trueexcept:print('API has not started. Still attempting to initialize it.')time.sleep(3)thread = threading.Thread(target=initialization)thread.start()if __name__ == '__main__':self_initialize()app.run(host='0.0.0.0',debug=True,threaded=True)

data_utils.py

data_utils.py文件不同于其以前的版本仅在加载从生产注册表模型中的一部分。区别在于:

  • status = storage.Blob(bucket=bucket, name='{}/{}'.format('testing',model_filename)).exists(storage_client) 经过 status = storage.Blob(bucket=bucket, name='{}/{}'.format('production',model_filename)).exists(storage_client)
  • blob1 = bucket.blob('{}/{}'.format('testing',model_filename)) by blob1 = bucket.blob('{}/{}'.format('production',model_filename))

Dockerfile

在我们的Dockerfile ,替换

RUN git clone https://github.com/sergiovirahonda/AutomaticTraining-Uni​​tTesting.git

RUN git clone https://github.com/sergiovirahonda/AutomaticTraining-PredictionAPI.git

在本地构建并运行容器后,您应该可以通过POST请求在http://172.17.0.2:5000/获得一个功能齐全的预测服务。

下一步

在接下来的系列文章中,我们将看到如何在Kubernetes、Jenkins和Google Cloud Platform的帮助下将各个容器链接到一个实际的管道中。敬请关注!

https://www.codeproject.com/Articles/5301650/Building-an-MLOps-Model-API

(六)构建MLOps模型API相关推荐

  1. 今晚直播 | 谷歌资深工程师手把手教你使用TensorFlow最新API构建学习模型

    目前,深度学习的研究和应用大受追捧,各种开源的深度学习框架层出不穷.TensorFlow 作为目前最受欢迎的深度学习框架,已经在 GitHub 上获得了 112194 个 star,受欢迎程序可见一斑 ...

  2. 【小白学习PyTorch教程】六、基于CIFAR-10 数据集,使用PyTorch 从头开始​​构建图像分类模型...

    「@Author:Runsen」 图像识别本质上是一种计算机视觉技术,它赋予计算机"眼睛",让计算机通过图像和视频"看"和理解世界. 在开始阅读本文之前,建议先 ...

  3. 【小白学习PyTorch教程】六、基于CIFAR-10 数据集,使用PyTorch 从头开始​​构建图像分类模型

    @Author:Runsen 图像识别本质上是一种计算机视觉技术,它赋予计算机"眼睛",让计算机通过图像和视频"看"和理解世界. 在开始阅读本文之前,建议先了解 ...

  4. python 加载动图_在浏览器中使用TensorFlow.js和Python构建机器学习模型(附代码)...

    大数据文摘授权转载自数据派THU 作者:MOHD SANAD ZAKI RIZVI 本文主要介绍了: TensorFlow.js (deeplearn.js)使我们能够在浏览器中构建机器学习和深度学习 ...

  5. 独家 | 在浏览器中使用TensorFlow.js和Python构建机器学习模型(附代码)

    作者:MOHD SANAD ZAKI RIZVI 翻译:吴金笛 校对:丁楠雅 本文约5500字,建议阅读15分钟. 本文首先介绍了TensorFlow.js的重要性及其组件,并介绍使用其在浏览器中构建 ...

  6. 实操指南:用谷歌AutoML构建图像分类模型

    2020-03-16 12:31:00 全文共2710字,预计学习时长8分钟 如何用谷歌AutoML创建单标签分类模型? 今天我们将使用一个来自generated.photos的AI生成的人脸数据集, ...

  7. 推荐11个构建和测试API的顶级工具

    点击蓝色"程序猿DD"关注我 回复"资源"获取独家整理的学习资料! >> 「开学季」当当大促!4-5折优惠不了解一下? << 立刻像专业 ...

  8. 建模揭秘----构建用户模型

    原文地址:http://www.ibm.com/developerworks/cn/architecture/ar-usermod2/?S_TACT=105AGX52&S_CMP=tec-cs ...

  9. django restful 请求_利用 Django REST framework 构建 RESTful Web API

    利用 Django REST framework 构建 RESTful Web API 终于到了动手操作的环节啦,这一节,我们以师生管理系统为例,带领大家搭建一套 framework Web API. ...

最新文章

  1. 求整型数组所有子串的和中的最大值
  2. XXL-JOB v2.0.2,分布式任务调度平台
  3. JAVA IF判断语句
  4. DeeCamp 2020启动,邀请全球AI菁英共克世界变局下真实难题!
  5. python的程序结构有哪几种_python异常处理结构有哪几种形式
  6. 给自定义控件(Web Control)添加事件的几种方法。前两种方法可以不实现IPostBackEventHandler...
  7. 实现DDD领域驱动设计: Part 2
  8. iOS--控制器加载自定义view的xib
  9. 可折叠的 iPhone 要来了?
  10. 安卓开发者必备的六个工具
  11. 函数WaitForMultipleObjects
  12. Native Instruments Flair for Mac - 老式模拟磁带和踏板效果器
  13. 盘点10款逆天级效率工具,能帮创业公司节省50%时间成本
  14. 应用程序无法正常启动 0xc0150002
  15. 估值模型不适用_十年十倍!绝对估值法是如何引领巴菲特买入可口可乐的?
  16. 基于python的音乐数据分析_基于Python的亚马逊音乐产品评论分析
  17. MutationObserver监测qrcodejs2二维码生成失败
  18. AndroidStudio合并冲突失败,总在merging状态
  19. markdown如何调整行距_反Markdown试验:用Markdown的思维来使用Word
  20. 计算机页面大小4k,4K分辨率到底是什么?简单告诉你

热门文章

  1. UI设计灵感|音乐播放器界面如何设计?
  2. 壁纸控的你需要看这里!
  3. 圣诞节海报这么做?不妨借鉴下这些模板!
  4. 频谱分析幅值单位_FFT分析的注意事项,您都知道吗?
  5. QT将绝对路径转成相对路径
  6. 基于HTML5的贪吃蛇游戏的设计与实现
  7. ncurses屏幕操作:getyx(),getparyx(),getmaxyx(),scr_dump(),scr_restore(),getwin(),putwin()
  8. php output详解,PHP输出缓冲控制Output Control系列函数详解,output函数详解
  9. ajax一步调用,ajax异步调用
  10. 启动mysq服务_mysql安装、启动