关于tensorflow图:我对这个程序有什么不对?

Xiu*_*ang 8 tensorflow

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)
Run Code Online (Sandbox Code Playgroud)

输出错误:

    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.)
Run Code Online (Sandbox Code Playgroud)

Cla*_*ash 8

这个错误实际上是在告诉你它失败的原因.当您启动会话时,您实际上使用的图形与引用的图形不同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)
Run Code Online (Sandbox Code Playgroud)

或者你也可以删除该行with tf.Graph().as_default():,然后它也将按预期工作.

  • 一个图可以有多个tf.Session()吗?因此我们可以构造相同的图并使用更多的地方? (2认同)

bar*_*ras 5

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

graph = tf.Graph()
with graph.as_default():
Run Code Online (Sandbox Code Playgroud)

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

with tf.Session(graph=graph) as session:
Run Code Online (Sandbox Code Playgroud)