昨晚终于实现了Tensorflow模型的部署 使用TensorFlow Serving

1、使用Docker 获取Tensorflow Serving的镜像,Docker在国内的需要将镜像的Repository地址设置为阿里云的加速地址,这个大家可以自己去CSDN上面找

然后启动docker

2、使用Tensorflow 的 SaveModelBuilder保存Tensorflow的计算图模型,并且设置Signature,

Signature主要用来标识模型的输入值的名称和类型

        builder = saved_model_builder.SavedModelBuilder(export_path)

        classification_inputs = utils.build_tensor_info(cnn.input_x)
classification_dropout_keep_prob = utils.build_tensor_info(cnn.dropout_keep_prob)
classification_outputs_classes = utils.build_tensor_info(prediction_classes)
classification_outputs_scores = utils.build_tensor_info(cnn.scores) classification_signature = signature_def_utils.build_signature_def(
inputs={signature_constants.CLASSIFY_INPUTS: classification_inputs,
signature_constants.CLASSIFY_INPUTS:classification_dropout_keep_prob
},
outputs={
signature_constants.CLASSIFY_OUTPUT_CLASSES:
classification_outputs_classes,
signature_constants.CLASSIFY_OUTPUT_SCORES:
classification_outputs_scores
},
method_name=signature_constants.CLASSIFY_METHOD_NAME) tensor_info_x = utils.build_tensor_info(cnn.input_x)
tensor_info_y = utils.build_tensor_info(cnn.predictions)
tensor_info_dropout_keep_prob = utils.build_tensor_info(cnn.dropout_keep_prob) prediction_signature = signature_def_utils.build_signature_def(
inputs={'inputX': tensor_info_x,
'input_dropout_keep_prob':tensor_info_dropout_keep_prob},
outputs={'predictClass': tensor_info_y},
method_name=signature_constants.PREDICT_METHOD_NAME) legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op') #add the sigs to the servable
builder.add_meta_graph_and_variables(
sess, [tag_constants.SERVING],
signature_def_map={
'textclassified':
prediction_signature,
signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:
classification_signature,
},
legacy_init_op=legacy_init_op)
#save it!
builder.save(True)

保存之后的计算图的结构可以从下面这里看见,下面这里只给出模型的signature部分,因为signature里面定义了你到时候call restful接口的参数名称和类型

  signature_def {
key: "serving_default"
value {
inputs {
key: "inputs"
value {
name: "dropout_keep_prob:0"
dtype: DT_FLOAT
tensor_shape {
unknown_rank: true
}
}
}
outputs {
key: "classes"
value {
name: "index_to_string_Lookup:0"
dtype: DT_STRING
tensor_shape {
dim {
size: 1
}
}
}
}
outputs {
key: "scores"
value {
name: "output/scores:0"
dtype: DT_FLOAT
tensor_shape {
dim {
size: -1
}
dim {
size: 2
}
}
}
}
method_name: "tensorflow/serving/classify"
}
}
signature_def {
key: "textclassified"
value {
inputs {
key: "inputX"
value {
name: "input_x:0"
dtype: DT_INT32
tensor_shape {
dim {
size: -1
}
dim {
size: 40
}
}
}
}
inputs {
key: "input_dropout_keep_prob"
value {
name: "dropout_keep_prob:0"
dtype: DT_FLOAT
tensor_shape {
unknown_rank: true
}
}
}
outputs {
key: "predictClass"
value {
name: "output/predictions:0"
dtype: DT_INT64
tensor_shape {
dim {
size: -1
}
}
}
}
method_name: "tensorflow/serving/predict"
}
}
}

从上面的Signature定义可以看出 到时候call restfull 接口需要传两个参数,

int32类型的名称为inputX参数

float类型名称为input_drop_out_keep_prob的参数

上面的protocol buffer 中

textclassified表示使用TextCnn卷积神经网络来进行预测,然后预测功能的名称叫做textclassified

3、将模型部署到Tensorflow Serving 上面

首先把模型通过工具传输到docker上面

模型的结构如下

传到docker上面,然后在外边套一个文件夹名字起位模型的名字,叫做

text_classified_model
然后执行下面这条命令运行tensorflow/serving
docker run -p 8500:8500 --mount type=bind,source=/home/docker/model/text_classified_model,target=/mo
dels/text_classified_model -e MODEL_NAME=text_classified_model -t tensorflow/serving
source表示模型在docker上面的路径
target表示模型在docker中TensorFlow/serving container上面的路径

然后输入如下所示

上面显示运行了两个接口一个是REST API 接口,端口是8501

另一个是gRPC接口端口是8500

gRPC是HTTP/2协议,REST API 是HTTP/1协议

区别是gRPC只有POST/GET两种请求方式

REST API还有其余很多种 列如 PUT/DELETE 等

4、客户端调用gPRC接口

需要传两个参数,

一个是

inputX

另一个是

input_dropout_keep_prob
'''
Created on 2018年10月17日 @author: 95890
''' """Send text to tensorflow serving and gets result
""" # This is a placeholder for a Google-internal import. from grpc.beta import implementations
import tensorflow as tf
import data_helpers
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2
from tensorflow.contrib import learn
import numpy as np tf.flags.DEFINE_string("positive_data_file", "./data/rt-polaritydata/rt-polarity.pos", "Data source for the positive data.")
tf.flags.DEFINE_string("negative_data_file", "./data/rt-polaritydata/rt-polarity.neg", "Data source for the negative data.")
tf.flags.DEFINE_string('server', '192.168.99.100:8500',
'PredictionService host:port')
FLAGS = tf.flags.FLAGS x_text=[]
y=[]
max_document_length=40 def main(_): testStr =["wisegirls is its low-key quality and genuine"] if x_text.__len__()==0:
x_text, y = data_helpers.load_data_and_labels(FLAGS.positive_data_file, FLAGS.negative_data_file)
max_document_length = max([len(x.split(" ")) for x in x_text]) vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)
vocab_processor.fit(x_text)
x = np.array(list(vocab_processor.fit_transform(testStr))) host, port = FLAGS.server.split(':')
channel = implementations.insecure_channel(host, int(port))
stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)
request = predict_pb2.PredictRequest()
request.model_spec.name = "text_classified_model"
request.model_spec.signature_name = 'textclassified'
dropout_keep_prob = np.float(1.0) request.inputs['inputX'].CopyFrom(
tf.contrib.util.make_tensor_proto(x, shape=[1,40],dtype=np.int32)) request.inputs['input_dropout_keep_prob'].CopyFrom(
tf.contrib.util.make_tensor_proto(dropout_keep_prob, shape=[1],dtype=np.float)) result = stub.Predict(request, 10.0) # 10 secs timeout
print(result) if __name__ == '__main__':
tf.app.run()

调用的结果如下所示

outputs {
key: "predictClass"
value {
dtype: DT_INT64
tensor_shape {
dim {
size: 1
}
}
int64_val: 1
}
}
model_spec {
name: "text_classified_model"
version {
value: 1
}
signature_name: "textclassified"
}

从上面的结果可以看出,我们传入了一句话

wisegirls is its low-key quality and genuine

分类的结果

predictClass
int64_val: 1

分成第一类

这个真的是神经网络的部署呀。

啦啦啦 ,  Tensorflow真的很牛,上至浏览器,下到手机,一次训练,一次导出。处处运行。

没有不敢想,只有不敢做

The Full version can be find here

https://github.com/weizhenzhao/TextCNN_Tensorflow_Serving/tree/master

Thanks

WeiZhen

139、TensorFlow Serving 实现模型的部署(二) TextCnn文本分类模型的更多相关文章

  1. 使用PyTorch建立你的第一个文本分类模型

    概述 学习如何使用PyTorch执行文本分类 理解解决文本分类时所涉及的要点 学习使用包填充(Pack Padding)特性 介绍 我总是使用最先进的架构来在一些比赛提交模型结果.得益于PyTorch ...

  2. NLP学习(2)----文本分类模型

    实战:https://github.com/jiangxinyang227/NLP-Project 一.简介: 1.传统的文本分类方法:[人工特征工程+浅层分类模型] (1)文本预处理: ①(中文) ...

  3. tensorflow 模型保存与加载 和TensorFlow serving + grpc + docker项目部署

    TensorFlow 模型保存与加载 TensorFlow中总共有两种保存和加载模型的方法.第一种是利用 tf.train.Saver() 来保存,第二种就是利用 SavedModel 来保存模型,接 ...

  4. 深度学习之文本分类模型-前馈神经网络(Feed-Forward Neural Networks)

    目录 DAN(Deep Average Network) Fasttext fasttext文本分类 fasttext的n-gram模型 Doc2vec DAN(Deep Average Networ ...

  5. Caffe、TensorFlow、MXnet三个开源库对比+主流分类模型对比

    库名称 开发语言 支持接口 安装难度(ubuntu) 文档风格 示例 支持模型 上手难易 Caffe c++/cuda c++/python/matlab *** * *** CNN ** MXNet ...

  6. Python自然语言处理笔记【二】文本分类之监督式分类的细节问题

    一.选择正确的特征 1.建立分类器的工作中如何选择相关特征,并且为其编码来表示这些特征是首要问题. 2.特征提取,要避免过拟合或者欠拟合 过拟合,是提供的特征太多,使得算法高度依赖训练数据的特性,而对 ...

  7. CNN 文本分类模型优化经验——关键点:加卷积层和FC可以提高精度,在FC前加BN可以加快收敛,有时候可以提高精度,FC后加dropout,conv_1d的input维度加大可以提高精度,但是到256会出现OOM。

    network = tflearn.input_data(shape=[None, max_len], name='input') network = tflearn.embedding(networ ...

  8. 基于Text-CNN模型的中文文本分类实战 流川枫 发表于AI星球订阅

    Text-CNN 1.文本分类 转眼学生生涯就结束了,在家待就业期间正好有一段空闲期,可以对曾经感兴趣的一些知识点进行总结. 本文介绍NLP中文本分类任务中核心流程进行了系统的介绍,文末给出一个基于T ...

  9. 基于Text-CNN模型的中文文本分类实战

    Text-CNN 1.文本分类 转眼学生生涯就结束了,在家待就业期间正好有一段空闲期,可以对曾经感兴趣的一些知识点进行总结. 本文介绍NLP中文本分类任务中核心流程进行了系统的介绍,文末给出一个基于T ...

随机推荐

  1. numpy.hstack(tup)

    numpy.hstack(tup) Stack arrays in sequence horizontally (column wise). Take a sequence of arrays and ...

  2. ECharts 中的事件和行为

    在 ECharts 的图表中用户的操作将会触发相应的事件.开发者可以监听这些事件,然后通过回调函数做相应的处理,比如跳转到一个地址,或者弹出对话框,或者做数据下钻等等. 如下是一个绑定点击操作的示例. ...

  3. 如何计算java程序运行花了多长时间。加时间戳。

    long start = System.currentTimeMillis(); // 记录起始时间 try { Thread.sleep(5000); // 线程睡眠5秒,让运行时间不那么小 } c ...

  4. Linux 硬盘挂载(服务器重启自动挂载)

    1.先查看目前机器上有几块硬盘,及已挂载磁盘: fdisk -l 能够查看到当前主机上已连接上的磁盘,以及已经分割的磁盘分区.(下面以/dev/vdb磁盘进行分区.挂载为例,挂载点设置为/data) ...

  5. .NET Framework 2.0/3.0/3.5 以 v90 平台工具集为目标。请确保在计算机上安装了 Visual Studio 2008

    今天在Visual Studio2010下面开发C++应用的时候发现“.NET Framework 2.0/3.0/3.5 以 v90 平台工具集为目标.请确保在计算机上安装了 Visual Stud ...

  6. Python 输出百分比

    注:python3环境试验 0x00 使用参数格式化{:2%} {:.2%}: 显示小数点后2位 print('{:.2%}'.format(10/50)) #percent: 20.00% {:.0 ...

  7. Python核心技术与实战——十二|Python的比较与拷贝

    我们在前面已经接触到了很多Python对象比较的例子,例如这样的 a = b = a == b 或者是将一个对象进行拷贝 l1 = [,,,,] l2 = l1 l3 = list(l1) 那么现在试 ...

  8. Codeforces Round #593 (Div. 2) C. Labs A. Stones

    题目:https://codeforces.com/contest/1236/problem/A 思路:两种操作收益都是3 且都会消耗b 操作2对b消耗较小 则可优先选择操作2 再进行操作1 即可得到 ...

  9. Java并发编程实战 第16章 Java内存模型

    什么是内存模型 JMM(Java内存模型)规定了JVM必须遵循一组最小保证,这组保证规定了对变量的写入操作在何时将对其他线程可见. JMM为程序中所有的操作定义了一个偏序关系,称为Happens-Be ...

  10. 轻松获取LAMP,LNMP环境编译参数配置

    轻松获取LAMP,LNMP环境编译参数配置 作者:Mr.Xiong /分类:系统管理  字号:L M S     大家是否遇到过去了新公司,公司内的LAMP,LNMP等所有的环境都是配置好的(已经在提 ...