Explore Courses Blog Tutorials Interview Questions
+3 votes
in Machine Learning by (11.4k points)

After you train a model in Tensorflow:

  1. How do you save the trained model?

  2. How do you later restore this saved model?


1 Answer

+4 votes
by (33.1k points)
edited by
Best answer

TensorFlow is a free and open-source software library for dataflow and differentiable programming across a range of tasks. It has a huge number of in-built functions that can be used for machine learning applications. There are functions to save and restore the model.

To save the model:


The saver class used to save and restore variables. Every time we save a model. It forms a checkpoint. From checkpoints, we can restore our model. Saver can automatically number checkpoints with a provided counter.

For Example

v1 = tf.Variable(name='v1')

v2 = tf.Variable(name='v2') 

# Pass the variables as a dict: 

saver = tf.train.Saver({'v1': v1, 'v2': v2}) 

# Or pass them as a list. 

saver = tf.train.Saver([v1, v2]) 

# Passing a list is equivalent to passing a dict with the variable op names 

# as keys: 

saver = tf.train.Saver({ v for v in [v1, v2]})

To restore the model

The tf.train.Saver object not only saves variables to checkpoint files, but it also restores variables. The tf.train.Saver.restore method is used to restore variables from the checkpoint files:


# Create some variables. 

v1 = tf.get_variable("v1", shape=[3]) 

v2 = tf.get_variable("v2", shape=[5]) 

# Add ops to save and restore all the variables. 

saver = tf.train.Saver() 

# Later, launch the model, use the saver to restore variables from disk, and 

# do some work with the model. 

with tf.Session() as sess: 

# Restore variables from disk. 

saver.restore(sess, "/tmp/model.ckpt") 

print("Model restored.") 

# Check the values of the variables 

print("v1 : %s" % v1.eval()) 

print("v2 : %s" % v2.eval())

I hope you will understand TensorFlow save and restore function from this. More you can find here.

Learn TensorFlow with the help of this comprehensive video tutorial:

Browse Categories