Xiuyi Yang
Xiuyi Yang

Reputation: 3251

About tensorflow graph: what am I wrong with this program?

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)

output error:

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

Upvotes: 8

Views: 20830

Answers (2)

bartgras
bartgras

Reputation: 442

Another option is to initialize graph variable first:

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

and than pass it to your session:

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

Upvotes: 5

Clash
Clash

Reputation: 5025

The error is actually giving you a tip of why it's failing. When you started the session, you are actually using a different graph than the one referenced by res. The easiest solution is to simply move everything inside 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)

Alternatively you can also just remove the line with tf.Graph().as_default(): and then it will also worked as expected.

Upvotes: 8

Related Questions