Jimmy Valentine
Jimmy Valentine

Reputation: 61

Cannot execute sess.run after loading model in TensorFlow

Code I use to load the model:

graph1 = tf.get_default_graph()
with graph1.as_default():
  with tf.Session(graph=graph1) as sess:
    tf.saved_model.loader.load(sess,[tag_constants.SERVING],'/mnist/mnist_saved_model/')

    x = graph1.get_tensor_by_name("x:0")
    y = graph1.get_tensor_by_name("y:0")
    keep_prob = graph1.get_tensor_by_name("keep_prob:0")
    aug_img = graph1.get_tensor_by_name("aug_img:0")
    logits = graph1.get_tensor_by_name("logits/BiasAdd:0")

    feats = sess.run(logits,feed_dict={x:img,keep_prob:1.0})
    print feats

sess.run executes fine, when called from within the with tf.Session(graph=graph1) as sess block

But when using Jupyter Notebook, when I am trying to execute sess.run on another image in another cell below the above piece of code, separately:

with tf.Session(graph=graph1) as sess:
  feats = sess.run(logits,feed_dict={x:img,keep_prob:1.0})

Then I am getting an error

FailedPreconditionError: Attempting to use uninitialized value conv2/kernel

Why can't I execute sess.run elsewhere except in the first piece of code?

How to load the model and call it from anywhere in the code?

Upvotes: 1

Views: 55

Answers (1)

Siladittya
Siladittya

Reputation: 1205

Do like this:

graph1 = tf.get_default_graph()
sess = tf.Session(graph=graph1)
with graph1.as_default():
  tf.saved_model.loader.load(sess,[tag_constants.SERVING],'/mnist/mnist_saved_model/')

  x = graph1.get_tensor_by_name("x:0")
  y = graph1.get_tensor_by_name("y:0")
  keep_prob = graph1.get_tensor_by_name("keep_prob:0")
  aug_img = graph1.get_tensor_by_name("aug_img:0")
  logits = graph1.get_tensor_by_name("logits/BiasAdd:0")

  feats = sess.run(logits,feed_dict={x:img,keep_prob:1.0})
  print feats

Then run only this line:

feats = sess.run(logits,feed_dict={x:img,keep_prob:1.0})
print feats

No need to do sess = tf.Session(graph=graph1) again

Upvotes: 1

Related Questions