错误Tensor is not an element of this graph tensorflow

    xiaoxiao2021-12-14  20

    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 说明:此段代码,其实是描述的是,在默认的图上去定义了初始化操作,然后想在默认图上去执行res操作,注意res操作是在我们自定义的图上的。所以,当然是会报错的.

    修改一:

    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上运行init操作,也就是在默认图上执行session操作.

    修改二:

    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只和我们定义的图相关联,只执行我们定义在图内的操作,这样就不会报错.

    转载请注明原文地址: https://ju.6miu.com/read-971499.html

    最新回复(0)