一、保存模型
Tensorflow 使用tf.train.Saver类进行保存。
import tensorflow as tf
v1 = tf.Variable(tf.constant([6.0], shape=[1]), name = 'v1')
v2 = tf.Variable(tf.constant([2.0], shape=[1]), name = 'v2')
result = v1+v2
saver = tf.train.Saver()
with tf.Session() as sess:
tf.global_variables_initializer().run()
saver.save(sess, "./saver/model.ckpt")
一般保存四个文件,一个model.ckpt.meta,它保存了Tensorflow计算图的结构。其他两个model.ckpt开头的是保存变量的值。最后一个checkpoint保存了一个目录下所有的模型文件列表。
二、加载模型
加载一个已保存的模型
import tensorflow as tf
v1 = tf.Variable(tf.constant([6.0], shape=[1]), name = 'v1')
v2 = tf.Variable(tf.constant([2.0], shape=[1]), name = 'v2')
result = v1+v2
saver = tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess, "./saver/model.ckpt")
print(sess.run(result))
加载模型的代码中没有运行变量的初始化过程,而是将变量的值通过保存的模型加载进来。
如果不希望重新定义图上的运算,可以直接加载已经持久话的图。
saver = tf.train.import_meta_graph("./saver/model.ckpt.meta")
with tf.Session() as sess:
saver.restore(sess, "./saver/model.ckpt")
#通过张量的名称来获取张量
print(sess.run(tf.get_default_graph().get_tensor_by_name("add:0")))