How to use TensorFlow built-in parameter export and Import methods: Basic usage
If you're still struggling with how to save TensorFlow-trained model parameters, this is the way to do it.
The Saver class adds ops to save and restore variables to and from checkpoints. It also provides convenience methods to run these ops. Introduction from the official website.
Import TensorFlow as TF
"" "
variable declaration, example of operation declaration: W = tf.get_variable (name=" Vari_name ", shape=[], Dtype=tf.float32)
Initializes the OP declaration
"" "
#创建saver对象, which adds some op to save and restore model parameters
Saver = Tf.train.Saver () with
TF. Session () as Sess:
sess.run (init_op)
#训练模型 ...
#使用saver提供的简便方法去调用 Save op
saver.save (Sess, "Save_path/file_name.ckpt") #file_name. Ckpt If it does not exist, it is automatically created
#后缀可加可不加
now that the trained model parameters have been stored, let's take a look at how to invoke the trained parameters
when a variable is saved, the variable name is stored: value, key-value pair. Restore is also done according to Key-value (see)
Import TensorFlow as TF
"" "
variable Declaration, OP declaration
initialization Op Declaration" "
"
#创建saver object
saver = Tf.train.Saver ()
With TF. Session () as Sess:
sess.run (INIT_OP) #在这里, can execute this statement, or do not execute, even if executed, the value of the initialization will also be the value of restore to override
Saver.restore ( Sess, "Save_path/file_name.ckpt-???")
How to restore a subset of variables and initialize other variables using initialize OP
#想要实现这个功能的话, you must start with the saver constructor
saver=tf.train.saver ([sub_set])
init = tf.initialize_all_variables ()
With TF. Session () as Sess:
#这样你就可以使用restore的变量替换掉初始化的变量的值, while other initialized values are not affected
Sess.run (init)
if restor_from_ Checkpoint:
Saver.restore (Sess, "File.ckpt")
# train
saver.save (Sess, "file.ckpt")
References
Https://www.tensorflow.org/versions/r0.12/how_tos/variables/index.html#saving-and-restoring
Https://www.tensorflow.org/versions/r0.12/api_docs/python/state_ops.html#Saver