Using Tensorflow SavedModel Format to Save and Do Predictions
We are now trying to deploy our Deep Learning model onto Google Cloud. It is required to use Google Function to trigger the Deep Learning predictions. However, when pre-trained models are stored on cloud, it is impossible to get the exact directory path and restore the tensorflow session like what we did on local machine.
So we turn to use SavedModel, which is quite like a 'Prediction Mode' of tensorflow. According to official turotial: a SavedModel contains a complete TensorFlow program, including weights and computation. It does not require the original model building code to run, which makes it useful for sharing or deploying.
The Definition of our graph, just here to show the input and output tensors:
'''RNN Model Definition'''
tf.reset_default_graph()
''''''
#define inputs
tf_x = tf.placeholder(tf.float32, [None, window_size,1],name='x')
tf_y = tf.placeholder(tf.int32, [None, 2],name='y') cells = [tf.keras.layers.LSTMCell(units=n) for n in num_units]
stacked_rnn_cell = tf.keras.layers.StackedRNNCells(cells)
outputs, (h_c, h_n) = tf.nn.dynamic_rnn(
stacked_rnn_cell, # cell you have chosen
tf_x, # input
initial_state=None, # the initial hidden state
dtype=tf.float32, # must given if set initial_state = None
time_major=False, # False: (batch, time step, input); True: (time step, batch, input)
)
l1 = tf.layers.dense(outputs[:, -1, :],32,activation=tf.nn.relu,name='l1')
l2 = tf.layers.dense(l1,8,activation=tf.nn.relu,name='l6')
pred = tf.layers.dense(l2,2,activation=tf.nn.relu,name='pred') with tf.name_scope('loss'):
cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(labels=tf_y, logits=pred)
loss = tf.reduce_mean(cross_entropy)
tf.summary.scalar("loss",tensor=loss)
train_op = tf.train.AdamOptimizer(LR).minimize(loss)
accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(tf_y, axis=1), tf.argmax(pred, axis=1)), tf.float32)) init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
saver = tf.train.Saver()
Train and Save the model, we use simple_save:
sess = tf.Session()
sess.run(init_op) for i in range(0,n):
sess.run(train_op,{tf_x:batch_X , tf_y:batch_y})
...
tf.saved_model.simple_save(sess, 'simple_save/model', \
inputs={"x": tf_x},outputs={"pred": pred})
sess.close()
Restore and Predict:
with tf.Session(graph=tf.Graph()) as sess:
tf.saved_model.loader.load(sess, ["serve"], 'simple_save_test/model')
batch = sess.run('pred/Relu:0',feed_dict={'x:0':dataX.reshape([-1,24,1])})
print(batch)
Reference:
medium post: https://medium.com/@jsflo.dev/saving-and-loading-a-tensorflow-model-using-the-savedmodel-api-17645576527
The official tutorial of Tensorflow: https://www.tensorflow.org/guide/saved_model
Using Tensorflow SavedModel Format to Save and Do Predictions的更多相关文章
- [Tool] Enable Prettier in VSCode as Format on Save and add config files to gitingore
First of all, install Prettier extension: "Pettier - Code formatter". The open the VSCode ...
- vs code的使用(一) Format On Paste/Format On Save/ Format On Type
很多经典的问题可以搜索出来,但是一些很小的问题网上却没有答案 (这是最令人发狂的,这么简单,网上居然连个相关的信息都没有给出) (就比如我想保存后自动格式化,但网上的大部分都是如何取消保存后自动格式化 ...
- 135、TensorFlow SavedModel工具类的使用
# SavedModelBuilder 类提供了保存多个MetaGraphDef的功能 # MetaGraph是一个数据流图,加上它的关联变量,资产和标签 # 一个MetaGraphDef是一个协议缓 ...
- tensorflow 2.0 技巧 | 自定义tf.keras.Model的坑
自定义tf.keras.Model需要注意的点 model.save() subclass Model 是不能直接save的,save成.h5,但是能够save_weights,或者save_form ...
- Run Your Tensorflow Deep Learning Models on Google AI
People commonly tend to put much effort on hyperparameter tuning and training while using Tensoflow& ...
- Tensorflow 模型线上部署
获取源码,请移步笔者的github: tensorflow-serving-tutorial 由于python的灵活性和完备的生态库,使得其成为实现.验证ML算法的不二之选.但是工业界要将模型部署到生 ...
- Tensorflow 2.x入门教程
前言 至于为什么写这个教程,首先是为了自己学习做个记录,其次是因为Tensorflow的API写的很好,但是他的教程写的太乱了,不适合新手学习.tensorflow 1 和tensorflow 2 有 ...
- Tensorflow应用之LSTM
学习RNN时原理理解起来不难,但是用TensorFlow去实现时被它各种数据的shape弄得晕头转向.现在就结合一个情感分析的案例来了解一下LSTM的操作流程. 一.深度学习在自然语言处理中的应用 自 ...
- 基于Spark和Tensorflow构建DCN模型进行CTR预测
实验介绍 数据采用Criteo Display Ads.这个数据一共11G,有13个integer features,26个categorical features. Spark 由于数据比较大,且只 ...
随机推荐
- Elasticsearch7.X 入门学习第二课笔记----基本api操作和CRUD
原文:Elasticsearch7.X 入门学习第二课笔记----基本api操作和CRUD 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链 ...
- Asp.net中GridView使用详解(很全,很经典)
http://blog.csdn.net/hello_world_wusu/article/details/4052844 Asp.net中GridView使用详解 效果图参考:http://hi.b ...
- asp.net webapi自定义输出结果类似Response.Write()
asp.net webapi自定义输出结果类似Response.Write() [HttpGet] public HttpResponseMessage HelloWorld() { string ...
- linux测试 Sersync 是否正常
[root@SERSYNC web]# for i in {1..10000};do echo 123456 > /data/web/$i &>/dev/null;do ne [r ...
- OGG复制进程延迟不断增长
1.注意通过进程查找sql_id时,进程号要查询两次 2.杀进程的连接 https://www.cnblogs.com/kerrycode/p/4034231.html 参考资料 1.https:// ...
- ls 显示目录下的内容和文件相关属性信息
1.命令功能 ls命令是“list directory contents”,显示当前目录下的内容和文件属性. 2.语法格式 ls [option] file ls 选项 文件名 3.选项说明 ...
- AOP技术介绍--(AOP技术基础)
2.1 AOP技术起源 AOP技术的诞生并不算晚,早在1990年开始,来自Xerox Palo Alto Research Lab(即PARC)的研究人员就对面向对象思想的局限性进行了分 ...
- 前端每日实战:86# 视频演示如何用纯 CSS 创作一个方块旋转动画
效果预览 按下右侧的"点击预览"按钮可以在当前页面预览,点击链接可以全屏预览. https://codepen.io/comehope/pen/gjgyWm 可交互视频 此视频是可 ...
- docker设置proxy
该方法是持久化的,修改后会一直生效.该方法覆盖了默认的docker.service文件. 1. 为docker服务创建一个内嵌的systemd目录 mkdir -p /etc/systemd/syst ...
- 用于DataLoader的pytorch数据集
暂时介绍 image-mask型数据集, 以人手分割数据集 EGTEA Gaze+ 为例. 准备数据文件夹 需要将Image和Mask分开存放, 对应文件的文件名必须保持一致. 提醒: Mask 图像 ...