tensorflow提了供tf.train.saver类已完成variable的保存和加载。其中save方法可以用来将计算图中的variable全部或者部分存储到ckpt文件,restore方法可以将ckpt文件中的全部或者部分变量导入计算图中。按照官方定义ckpt文件的作用是: map variable names to tensor values 。
variable存储和加载的一组实验:
saver_test.py
import tensorflow as tf
# Create some variables.
v1 = tf.get_variable("v1", shape=[3], initializer = tf.zeros_initializer)
v2 = tf.get_variable("v2", shape=[5], initializer = tf.zeros_initializer)
v3 = tf.get_variable("v3", shape=[4], initializer = tf.zeros_initializer)
inc_v1 = v1.assign(v1+1)
dec_v2 = v2.assign(v2-1)
dec_v3 = v3.assign(v3-2)
# Add an op to initialize the variables.
init_op = tf.global_variables_initializer()
# Add ops to save and restore all the variables.
saver = tf.train.Saver()
# Later, launch the model, initialize the variables, do some work, and save the
# variables to disk.
with tf.Session() as sess:
sess.run(init_op)
# Do some work with the model.
inc_v1.op.run()
dec_v2.op.run()
dec_v3.op.run()
print sess.run(v1)
print sess.run(v2)
print sess.run(v3)
# Save the variables to disk.^
save_path = saver.save(sess, "./saved_model/model.ckpt")
print("Model saved in file: %s" % save_path)
restore_test.py
import tensorflow as tf
tf.reset_default_graph()
# Create some variables.
v1 = tf.get_variable(