Tensor is not an element of this graph tensorflow/Failed to create session.

Tensor is not an element of this graph tensorflow / Failed to create session.

在运行Tensorflow时,遇到Tensor is not an element of this graph tensorflow/Failed to create session问题。基于 https://blog.csdn.net/lujiandong1/article/details/53448012 博主博客的基础上,进行扩展。

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)

这样运行会报错:
tensorflow.python.framework.errors_impl.InternalError: Failed to create session.
因为,with tf.Session() as sess: 与with tf.Graph().as_default():相当于这sess是新建了一个图,与with tf.Graph().as_default()不是一个图。但是去掉with tf.Graph().as_default():后:

import tensorflow as tf
def activation(e, f, g):
    return e + f + g
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)

这样会正常运行,因此这样所有的op都只会在默认的graph存在。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值