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的更多相关文章

  1. [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 ...

  2. vs code的使用(一) Format On Paste/Format On Save/ Format On Type

    很多经典的问题可以搜索出来,但是一些很小的问题网上却没有答案 (这是最令人发狂的,这么简单,网上居然连个相关的信息都没有给出) (就比如我想保存后自动格式化,但网上的大部分都是如何取消保存后自动格式化 ...

  3. 135、TensorFlow SavedModel工具类的使用

    # SavedModelBuilder 类提供了保存多个MetaGraphDef的功能 # MetaGraph是一个数据流图,加上它的关联变量,资产和标签 # 一个MetaGraphDef是一个协议缓 ...

  4. tensorflow 2.0 技巧 | 自定义tf.keras.Model的坑

    自定义tf.keras.Model需要注意的点 model.save() subclass Model 是不能直接save的,save成.h5,但是能够save_weights,或者save_form ...

  5. Run Your Tensorflow Deep Learning Models on Google AI

    People commonly tend to put much effort on hyperparameter tuning and training while using Tensoflow& ...

  6. Tensorflow 模型线上部署

    获取源码,请移步笔者的github: tensorflow-serving-tutorial 由于python的灵活性和完备的生态库,使得其成为实现.验证ML算法的不二之选.但是工业界要将模型部署到生 ...

  7. Tensorflow 2.x入门教程

    前言 至于为什么写这个教程,首先是为了自己学习做个记录,其次是因为Tensorflow的API写的很好,但是他的教程写的太乱了,不适合新手学习.tensorflow 1 和tensorflow 2 有 ...

  8. Tensorflow应用之LSTM

    学习RNN时原理理解起来不难,但是用TensorFlow去实现时被它各种数据的shape弄得晕头转向.现在就结合一个情感分析的案例来了解一下LSTM的操作流程. 一.深度学习在自然语言处理中的应用 自 ...

  9. 基于Spark和Tensorflow构建DCN模型进行CTR预测

    实验介绍 数据采用Criteo Display Ads.这个数据一共11G,有13个integer features,26个categorical features. Spark 由于数据比较大,且只 ...

随机推荐

  1. [AGC005F] Many Easy Problems

    link 题意简述 给定一颗无根树,对于所有大小为 $i$ 的点集,求出能够包含它的所有联通块之和,定义为 $f_i$ ,答案对 $924844033$ 取模. $n\leq 2\times 10^5 ...

  2. Latex--入门系列一

    Latex 专业的参考 tex对于论文写作或者其他的一些需要排版的写作来说,还是非常有意义的.我在网上看到这个对于Latex的入门介绍还是比较全面的,Arbitrary reference .所以将会 ...

  3. jquery 使用a标签导航栏跳转页面,动态添加高亮

    众所周知,使用a标签跳转之后,会刷新一次,继而这个添加的样式就会消失.那么怎么解决这一问题呢? <script> $(function () { $('.bar a').each(func ...

  4. Simple Vedio Intercom System

    I. Deployment  / Architecture Block Diagram II. Resources Used sip proxy server + sip user agent 1.  ...

  5. 【改】linux中分区的概念

    1.目录和分区 区别:Linux的分区是物理上的概念,从物理上将存储空间分开:Linux的目录是逻辑上的概念,Linux的目录树实际上是一个分区之间的数据逻辑结构关系,不是物理结构: 联系:一个分区必 ...

  6. linux7 grub配置文件 linux6 grub配置文件

    在 grub 的 kernel 配置后面,添加 acpi_pad.disable=1 重启机器之后,开机就不会自动加载 acpi_pad 模块 一:linux6 [root@node2 ~]# cat ...

  7. Java EE的优越性主要表现在哪些方面

    J2 EE的优越性主要表现在哪些方面 J2EE基于JAVA 技术,与平台无关. J2EE拥有开放标准,许多大型公司实现了对该规范支持的应用服务器.如BEA ,IBM,ORACLE等. J2EE提供相当 ...

  8. 【leetcode】1093. Statistics from a Large Sample

    题目如下: We sampled integers between 0 and 255, and stored the results in an array count:  count[k] is ...

  9. NIO编程之多客户端聊天系统

    1. 服务端 import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; im ...

  10. char* 和 cha[]

    char* s1 = "hello";//字符串常量 s是一个保存了字符串首地址的指针变量,同时也是字符串的名字,s的内容是第一个字符的地址,当s指向常量字符串时候,内容不能改变( ...