[专题2]tensorflow model save and restore 模型的保存和恢复(1)

Tensorflow: how to save/restore a model?


PS  马上要锁门了,先把代码 贴出来,.

一、入门

Question:

After you train a model in Tensorflow:

1. How do you save the trained model?

2. How do you later restore this saved model?

程序设计目标:

使用saver.save() 保存简单的模型

并使用

saver = tf.train.import_meta_graph('保存的模型文件')

saver.restore(sess,tf.train.latest_checkpoint('指定CKPT文件'))

Save Model


import tensorflow as tf

# 定义要占位的变量 , i.e. feed_dict and placeholders

w1 = tf.placeholder("float", name="w1")

w2 = tf.placeholder("float", name="w2")

b1= tf.Variable(2.0,name="bias")

feed_dict ={w1:4,w2:8}

# 定义要保存的操作

w3 = tf.add(w1,w2)

w4 = tf.multiply(w3,b1,name="op_to_restore")

sess = tf.Session()

sess.run(tf.global_variables_initializer())

# 创建saver 对象保存

saver = tf.train.Saver()

# 运行

print(sess.run(w4,feed_dict))

#Prints 24 which is sum of (w1+w2)*b1

#保存图 my_test_model是指定保存模型的路径

saver.save(sess, './my_test_model',global_step=1000)

Restore the model:

import tensorflow as tf

sess=tf.Session()

# 首先加载模型 ,注意这里要说明加载的文件

saver = tf.train.import_meta_graph('./my_test_model-1000.meta')

saver.restore(sess,tf.train.latest_checkpoint('./'))

# 访问模型的中的变量

print(sess.run('bias:0'))

# 会打印出 2, 这个是在上一段程序中保存过的变量

# Now, let's access and create placeholders variables and

# create feed-dict to feed new data

graph = tf.get_default_graph()

w1 = graph.get_tensor_by_name("w1:0")

w2 = graph.get_tensor_by_name("w2:0")

feed_dict ={w1:13.0,w2:17.0}

#Now, access the op that you want to run.

op_to_restore = graph.get_tensor_by_name("op_to_restore:0")

print sess.run(op_to_restore,feed_dict)

#This will print 60 which is calculated

相关参考文献:

save-restore-tensorflow-models-quick-complete-tutoria

tensorflow-how-to-save-restore-a-model

你可能感兴趣的:([专题2]tensorflow model save and restore 模型的保存和恢复(1))