class tf.train.Saver
功能:通过保存和重新加载模型(模型参数:计算图的结构和图上参数取值)实现模型持久化。
说明: tf.train.Saver目前版本为V2.0,相比V1.0的主要区别在于:
V2.0版本保存后文件夹中会比V1.0版本多一个model.ckpt.data-00000-of-00001文件.
例子:
import tensorflow as tf
import numpy as np
#step1:保存模型
W=tf.Variable([[1,2,3],[4,5,6]],dtype=tf.float32,name='weights')
b=tf.Variable([[1,2,3]],dtype=tf.float32,name='biases')
init=tf.global_variables_initializer()
saver=tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
save_path=saver.save(sess,"savepath(例如:"C:\\Desktop\\test.ckpt\\")")
print("Save to path:",save_path)
#step2:重新加载模型
#注:需要定义同样的数据类型和shape!
W=tf.Variable(np.arange(6).reshape((2,3)),dtype=tf.float32,name="weights")
b=tf.Variable(np.arange(3).reshape((1,3)),dtype=tf.float32,name="biases")
saver=tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess,"C:\\Desktop\\test.ckpt\\")
print("weights:",sess.run(W))
print("biases:",sess.run(b))
结果:
weights: [[ 1. 2. 3.]
[ 4. 5. 6.]]
biases: [[ 1. 2. 3.]]
注:首先运行step1将模型数据存储到指定路径上,其次再对路径上的数据进行调用加载。