【问题标题】:About tensorflow graph: what am I wrong with this program?关于张量流图:我对这个程序有什么问题?
【发布时间】:2016-03-06 12:06:23
【问题描述】:
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.)

【问题讨论】:

  • 以 tf.Session(graph=graph) 作为 sess:

标签: tensorflow


【解决方案1】:

这个错误实际上是在告诉你它失败的原因。当您开始会话时,您实际上使用的图表与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(): 行,然后它也会按预期工作。

【讨论】:

  • 一个图可以有多个tf.Session()吗?所以我们可以构建相同的图表并使用更多的地方?
  • 你怎么知道它使用了来自抱怨错误的另一个图表?
  • 这令人困惑。最初您说的是“使用 tf.Graph().as_default(): 将所有内容移到里面”。稍后您会说“或者,您也可以使用 tf.Graph().as_default(): 删除该行”。那么两者都可以吗?那你说什么呢?
【解决方案2】:

另一种选择是先初始化图形变量:

graph = tf.Graph()
with graph.as_default():

然后将其传递给您的会话:

with tf.Session(graph=graph) as session:

【讨论】:

    猜你喜欢
    • 2017-12-13
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    相关资源
    最近更新 更多