Tensor is not an element of this graph tensorflow / Failed to create session.
在运行Tensorflow时,遇到Tensor is not an element of this graph tensorflow/Failed to create session问题。基于 https://blog.csdn.net/lujiandong1/article/details/53448012 博主博客的基础上,进行扩展。
import tensorflow as tf
def activation(e, f, g):
return e + f + g
with tf.Graph().as_default():
a = tf.constant([5, 4, 5], name='a')
b = tf.constant([0, 1, 2], name='b')
c = tf.constant([5, 0, 5], name='c')
res = activation(a, b, c)
init = tf.initialize_all_variables()
with tf.Session() as sess: # Start running operations on the Graph.
sess.run(init)
hi = sess.run(res)
print (hi)
这样运行会报错:
tensorflow.python.framework.errors_impl.InternalError: Failed to create session.
因为,with tf.Session() as sess: 与with tf.Graph().as_default():相当于这sess是新建了一个图,与with tf.Graph().as_default()不是一个图。但是去掉with tf.Graph().as_default():后:
import tensorflow as tf
def activation(e, f, g):
return e + f + g
a = tf.constant([5, 4, 5], name='a')
b = tf.constant([0, 1, 2], name='b')
c = tf.constant([5, 0, 5], name='c')
res = activation(a, b, c)
init = tf.initialize_all_variables()
with tf.Session() as sess: # Start running operations on the Graph.
sess.run(init)
hi = sess.run(res)
print (hi)
这样会正常运行,因此这样所有的op都只会在默认的graph存在。