Explain tensorflow's model saving and invocation instances

  • 2020-11-20 06:10:35
  • OfStack

tensorflow is usually used for training. After training, the model should be saved, i.e. the memory of the model (weight and bias), so that it can be used for face recognition or speech recognition.

1. Model saving


#  Declare two variables 
v1 = tf.Variable(tf.random_normal([1, 2]), name="v1")
v2 = tf.Variable(tf.random_normal([2, 3]), name="v2")
init_op = tf.global_variables_initializer() #  Initializes all variables 
saver = tf.train.Saver() #  The statement tf.train.Saver Class is used to store the model 
with tf.Session() as sess:
 sess.run(init_op)
 print("v1:", sess.run(v1)) #  print v1 , v2 The value of the 1 It will read and compare 
 print("v2:", sess.run(v2))
  # Define the save path, 1 Must be an absolute path, and use ' / ' Separate parent and child directories 
 saver_path = saver.save(sess, "C:/Users/Administrator/Desktop/tt/model.ckpt") #  Save the model to save/model.ckpt file 
 print("Model saved in file:", saver_path)

2. Model reading

When I read the model directly, I may report an error. I compiled with Spyder, so I can turn off Spyder and turn it back on, and then I can read the data. The reason may be that the variable was initialized when the model was saved.


import tensorflow as tf

#  Use and save the model code 1 A way to declare variables 
v1 = tf.Variable(tf.random_normal([1, 2]), name="v1")
v2 = tf.Variable(tf.random_normal([2, 3]), name="v2")
saver = tf.train.Saver() #  The statement tf.train.Saver Class is used to store the model 
with tf.Session() as sess:
 saver.restore(sess, "C:/Users/Administrator/Desktop/tt/model.ckpt") #  Is about to solidify into a hard disk Session Read from the save path 
 print("v1:", sess.run(v1)) #  print v1 , v2 And compare it to the previous one 
 print("v2:", sess.run(v2))
 print("Model Restored")

Related articles: