0

I am trying to run the conviz.py code posted on https://github.com/grishasergei/conviz. The code returns "RuntimeError: Attempted to use a closed Session

Note : I am using python 3.6 and TensorFlow 1.13.1.

I simply cloned the GitHub source and ran it with minor modifications. (e.g incompatibility issues in xrange and cross_entropy part)

Here is the part of the code that seems to be related to the error.

with tf.Session() as sess:
    sess.run(init)
    step = 1
    # Keep training until reach max iterations
    while step * batch_size < training_iters:
        batch_x, batch_y = mnist.train.next_batch(batch_size)
        # Run optimization op (backprop)
        sess.run(optimizer, feed_dict={x: batch_x, y: batch_y,
                                       keep_prob: dropout})
        if step % display_step == 0:
            # Calculate batch loss and accuracy
            loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,
                                                              y: batch_y,
                                                              keep_prob: 1.})
            print("\rIter " + str(step*batch_size) + ", Minibatch Loss= " +
                  "{:.6f}".format(loss) + ", Training Accuracy= " +
                  "{:.5f}".format(acc), end='')
        step += 1
    print("\rOptimization Finished!")

# Calculate accuracy for 256 mnist test images
print("Testing Accuracy:",
      sess.run(accuracy, feed_dict={x: mnist.test.images[:256],
                                    y: mnist.test.labels[:256],
                                    keep_prob: 1.}))

# no need for feed dictionary here
conv_weights = sess.run([tf.get_collection('conv_weights')])
print("conv_weights done!")
for i, c in enumerate(conv_weights[0]):
    plot_conv_weights(c, 'conv{}'.format(i))

I expected conv_weights = sess.run([tf.get_collection('conv_weights')]) would load the weights tensor, but the code resulted in the following stack trace.

cell_name in async-def-wrapper()

/opt/conda/envs/Python36/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    927     try:
    928       result = self._run(None, fetches, feed_dict, options_ptr,
--> 929                          run_metadata_ptr)
    930       if run_metadata:
    931         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/opt/conda/envs/Python36/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1073     # Check session.
   1074     if self._closed:
-> 1075       raise RuntimeError('Attempted to use a closed Session.')
   1076     if self.graph.version == 0:
   1077       raise RuntimeError('The Session graph is empty.  Add operations to the '
1
  • In your print statement, you use the session outside the tf.Session context. Commented Oct 25, 2019 at 2:36

1 Answer 1

1

You should be to change code like below, sess object must be inside at "with tf.Session() as sess:":

with tf.Session() as sess:
    sess.run(init)
    step = 1
    # Keep training until reach max iterations
    while step * batch_size < training_iters:
        batch_x, batch_y = mnist.train.next_batch(batch_size)
        # Run optimization op (backprop)
        sess.run(optimizer, feed_dict={x: batch_x, y: batch_y,
                                   keep_prob: dropout})
        if step % display_step == 0:
            # Calculate batch loss and accuracy
            loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,
                                                          y: batch_y,
                                                          keep_prob: 1.})
            print("\rIter " + str(step*batch_size) + ", Minibatch Loss= " +
              "{:.6f}".format(loss) + ", Training Accuracy= " +
              "{:.5f}".format(acc), end='')
        step += 1
    print("\rOptimization Finished!")
    # Calculate accuracy for 256 mnist test images
    print("Testing Accuracy:",
    sess.run(accuracy, feed_dict={x: mnist.test.images[:256],
                                y: mnist.test.labels[:256],
                                keep_prob: 1.}))
    # no need for feed dictionary here
    conv_weights = sess.run([tf.get_collection('conv_weights')])
    print("conv_weights done!")
    for i, c in enumerate(conv_weights[0]):
        plot_conv_weights(c, 'conv{}'.format(i))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.