1、说明:tensorflow使用图来定义计算,在session中来执行图中定义的计算,如果没有显式的说明,那么session就跟默认的图相关联.graph 和 session应该是一一对应的.下面,举例说明,session如果和graph不一一对应的话,会出现error
- 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
说明:运行该脚本会报错: is not an element of this graph。该错误的意思就是说操作不在图中,也就是和我们的session相关联的图中并没有该操作.why?
2、分析原因:
首先,tensorflow会为我们指定一张默认的图.然后sesssion会直接和该默认图相关联.除非我们自定义一张图.不然,我们的操作都是在那张默认图上的.然后我们分析报错的代码:
- 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
修改一:
- 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
修改二:
- 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
说明:把所有的操作都定义在我们指定的图上面,并且,session也定义在缩进内,相当于该session只和我们定义的图相关联,只执行我们定义在图内的操作,这样就不会报错.