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.
merged = tf.merge_all_summaries()
sess.run(init)
hi = sess.run(res)
print hi
writer = tf.train.SummaryWriter("/tmp/basic", sess.graph_def)
输出错误:
Value Error: Fetch argument <tf.Tensor 'add_1:0' shape=(3,) dtype=int32> of
<tf.Tensor 'add_1:0' shape=(3,) dtype=int32> cannot be interpreted as a Tensor.
(Tensor Tensor("add_1:0", shape=(3,), dtype=int32) is not an element of this graph.)
答案 0 :(得分:7)
该错误实际上是在告诉您失败的原因。当您启动会话时,实际上使用的图形与res
引用的图形不同。最简单的解决方案是简单地将所有内容移到with tf.Graph().as_default():
。
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.
merged = tf.merge_all_summaries()
sess.run(init)
hi = sess.run(res)
print hi
writer = tf.train.SummaryWriter("/tmp/basic", sess.graph_def)
或者您也可以删除行with tf.Graph().as_default():
,然后它也会按预期工作。
答案 1 :(得分:4)
另一种选择是首先初始化图形变量:
graph = tf.Graph()
with graph.as_default():
并将其传递给您的会话:
with tf.Session(graph=graph) as session: