tensorflow 训练模型与预测模型不能同时运行解决办法,否则报错kernel already exists, disallowed. Did you mean to set reuse=True

https://blog.csdn.net/u010420283/article/details/80295270

1: 2
1ValueError: Variable model/rnn/multi_rnn_cell/cell_0/basic_lstm_cell/kernel already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope? Originally defined at: 2 3 File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 2005, in __init__ 4 self._traceback = tf_stack.extract_stack() 5 File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 3616, in create_op 6 op_def=op_def) 7 File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\util\deprecation.py", line 507, in new_func 8 return func(*args, **kwargs) 9 File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 788, in _apply_op_helper 10 op_def=op_def) 11 File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_state_ops.py", line 2023, in variable_v2 12 shared_name=shared_name, name=name) 13 14解决方法 15  16

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.

1with tf.Session() as sess: 2 sess.run(init) 3 step = 1 4 # Keep training until reach max iterations 5 while step * batch_size < training_iters: 6 batch_x, batch_y = mnist.train.next_batch(batch_size) 7 # Run optimization op (backprop) 8 sess.run(optimizer, feed_dict={x: batch_x, y: batch_y, 9 keep_prob: dropout}) 10 if step % display_step == 0: 11 # Calculate batch loss and accuracy 12 loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x, 13 y: batch_y, 14 keep_prob: 1.}) 15 print("\rIter " + str(step*batch_size) + ", Minibatch Loss= " + 16 "{:.6f}".format(loss) + ", Training Accuracy= " + 17 "{:.5f}".format(acc), end='') 18 step += 1 19 print("\rOptimization Finished!") 20 21# Calculate accuracy for 256 mnist test images 22print("Testing Accuracy:", 23 sess.run(accuracy, feed_dict={x: mnist.test.images[:256], 24 y: mnist.test.labels[:256], 25 keep_prob: 1.})) 26 27# no need for feed dictionary here 28conv_weights = sess.run([tf.get_collection('conv_weights')]) 29print("conv_weights done!") 30for i, c in enumerate(conv_weights[0]): 31 plot_conv_weights(c, 'conv{}'.format(i)) 32

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.

1cell_name in async-def-wrapper() 2 3/opt/conda/envs/Python36/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata) 4 927 try: 5 928 result = self._run(None, fetches, feed_dict, options_ptr, 6--> 929 run_metadata_ptr) 7 930 if run_metadata: 8 931 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) 9 10/opt/conda/envs/Python36/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata) 11 1073 # Check session. 12 1074 if self._closed: 13-> 1075 raise RuntimeError('Attempted to use a closed Session.') 14 1076 if self.graph.version == 0: 15 1077 raise RuntimeError('The Session graph is empty. Add operations to the ' 16

python tensorflow session runtime

shareeditfollow

Get updates on questions and answers

asked Oct 25 '19 at 2:17

uploading.4e448015.gif 转存失败重新上传取消

Daesung

1

  • In your print statement, you use the session outside the tf.Session context. – zihaozhihao Oct 25 '19 at 2:36

add a comment

1 Answer

ActiveOldestVotes

0

 

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

1with tf.Session() as sess: 2 sess.run(init) 3 step = 1 4 # Keep training until reach max iterations 5 while step * batch_size < training_iters: 6 batch_x, batch_y = mnist.train.next_batch(batch_size) 7 # Run optimization op (backprop) 8 sess.run(optimizer, feed_dict={x: batch_x, y: batch_y, 9 keep_prob: dropout}) 10 if step % display_step == 0: 11 # Calculate batch loss and accuracy 12 loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x, 13 y: batch_y, 14 keep_prob: 1.}) 15 print("\rIter " + str(step*batch_size) + ", Minibatch Loss= " + 16 "{:.6f}".format(loss) + ", Training Accuracy= " + 17 "{:.5f}".format(acc), end='') 18 step += 1 19 print("\rOptimization Finished!") 20 # Calculate accuracy for 256 mnist test images 21 print("Testing Accuracy:", 22 sess.run(accuracy, feed_dict={x: mnist.test.images[:256], 23 y: mnist.test.labels[:256], 24 keep_prob: 1.})) 25 # no need for feed dictionary here 26 conv_weights = sess.run([tf.get_collection('conv_weights')]) 27 print("conv_weights done!") 28 for i, c in enumerate(conv_weights[0]): 29 plot_conv_weights(c, 'conv{}'.format(i)) 30

 

代码交流 2021