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. Segment tree Beats

    Segment tree Beats Segment tree Beats,吉司机线段树,主要是关于如何用线段树实现区间取min/max.我们先看一道例题: HDU5306 Gorgeous Sequ ...

  2. [常用类]Math、Random、System、BigInteger、BigDecimal

    Math类中的成员全是静态成员,构造方法是 私有的,以避免被创建对象 常用方法: int abs() double ceil() //向上取整 double floor() //向下取整 int ma ...

  3. markDown 生成带侧边栏的目录

    1.首先安装马克飞象 2.第二步安装 npm install -g i5ting_toc 3.进入 md 文件所在的文件夹后, 输入命令:   i5ting_toc -f sample.md -o s ...

  4. Mysql共享锁、排他锁、悲观锁、乐观锁

    一.相关名词 |--表级锁(锁定整个表) |--页级锁(锁定一页) |--行级锁(锁定一行) |--共享锁(S锁,MyISAM 叫做读锁) |--排他锁(X锁,MyISAM 叫做写锁) |--间隙锁( ...

  5. spring data jpa和spring data redis同时配置时,出现Multiple Spring Data modules found, entering strict repository configuration mode错误

    问题说明 data jpa和data redis同时配置时,出现Spring modules spring Spring Data Release Train <dependencyManage ...

  6. 网络拓扑_配置VLAN虚拟局域网

    目的: 1.创建VLAN10,VALN20,VLAN30; 2.将端口加入VLAN 3.查看VLAN信息 拓扑图: 步骤: 1.在三层交换机中创建VLAN10,VLAN20,VLAN30 <Hu ...

  7. JAVA 关于File的使用

    File中常用方法 创建 createNewFile() 在指定位置创建一个空文件,成功就返回true,如果已存在就不创建然后返回false mkdir() 在指定位置创建目录,这只会创建最后一级目录 ...

  8. 【leetcode】1041. Robot Bounded In Circle

    题目如下: On an infinite plane, a robot initially stands at (0, 0) and faces north.  The robot can recei ...

  9. 对webpack的初步研究2

    Entry Points 如“ 入门”中所述,有多种方法可以entry在webpack配置中定义属性.我们会告诉你,你的方法可以配置的entry属性,除了解释为什么它可能对你有用 Single Ent ...

  10. c#代码规则,C#程序中元素的命名规范

    俩种命名方法 1.Pascal 命名法,第一个字母大写其它字母小写Userid 2.Camel命名法,所有单第一方写大写,其它小写,骆峰命名法,userId C#程序中元素的命名规范项目名:公司名.项 ...