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

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

:
ValueError: 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:
    
      File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 2005, in __init__
        self._traceback = tf_stack.extract_stack()
      File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 3616, in create_op
        op_def=op_def)
      File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\util\deprecation.py", line 507, in new_func
        return func(*args, **kwargs)
      File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 788, in _apply_op_helper
        op_def=op_def)
      File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_state_ops.py", line 2023, in variable_v2
        shared_name=shared_name, name=name)

解决方法
     遇到这种报错,只要在代码开头加上:tf.reset_default_graph()   #加入这句话,可以重新创建图,否则会报错

参考
   https://blog.csdn.net/mr_brooks/article/details/80393396
    解决办法二   将with session 后面的代码,全部缩进到session的作用域内部

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 '

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:":

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))

 

你可能感兴趣的:(tensorflow)