RuntimeError: The Session graph is empty. Add operations to the graph before calling run().

RuntimeError: The Session graph is empty. Add operations to the graph before calling run().

执行sess.run()报错

import tensorflow.compat.v1 as tf
hello = tf.constant('Hello tensorflow')
sess = tf.Session()
print(sess.run(hello))
sess.close()

在这里插入图片描述
中文意思:会话图为空。在调用run()之前将操作添加到图中。
在这里插入图片描述
问题产生的原因:无法执行sess.run()的原因是tensorflow版本不同导致的,tensorflow版本2.0无法兼容版本1.0.

解决方案:

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()  #保证sess.run()能够正常运行
hello = tf.constant('Hello tensorflow')
sess = tf.Session()
print(sess.run(hello))
sess.close()

在这里插入图片描述
建议:tf2.X与1.X还是有很多不同,每次错误的地方,都要有意识的记忆,这也是成为优秀程序员的必经之路。不要一股脑的就百度找答案,先理解中文意思,然后尝试自己解决一下,会很有帮助。
在这里插入图片描述

  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
这个错误通常出现在使用 TensorFlow 时,因为 TensorFlow 的运行过程中需要先构建计算图(computational graph),然后再运行。如果构建的计算图为空,就会出现这个错误。 要解决这个错误,你需要确保在调用 `run()` 方法之前,已经构建好了计算图。可以通过以下方式来构建计算图: 1. 定义计算图中的所有操作(包括输入数据和模型),并将它们添加到默认图中。 2. 开始一个会话(Session)。 3. 在会话中运行计算图。 以下是一个简单的 TensorFlow 示例代码,演示如何构建计算图和运行会话: ```python import tensorflow as tf # 定义计算图中的操作 x = tf.placeholder(tf.float32, shape=[None, 784]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.nn.softmax(tf.matmul(x, W) + b) # 开始一个会话 with tf.Session() as sess: # 初始化所有变量 sess.run(tf.global_variables_initializer()) # 运行计算图 result = sess.run(y, feed_dict={x: some_input_data}) ``` 在这个示例中,`x` 是一个占位符(placeholder),它表示输入数据的形状。`W` 和 `b` 是可以训练的变量,它们的初始值是全零。`y` 是一个 softmax 操作,它将输入数据与权重矩阵相乘并加上偏置向量,然后进行 softmax 操作得到输出。 在会话中,我们首先初始化所有变量,然后运行计算图,并将输入数据传递给占位符。最终的结果保存在 `result` 中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

积跬步至万里

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值