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

问题与解决

今天根据 https://blog.csdn.net/Cs_hnu_scw/article/details/79695347(在此感谢博主,虽然因为时间问题根据教程出现了很多问题,但还是帮了我很多忙)这篇文章安装 Tensorflow 时,为了尝试安装是否成功,编译了博主提供的 pycharm 测试代码

import tensorflow as tf
import os
os.environ[‘TF_CPP_MIN_LOG_LEVEL’]=‘2’
hello=tf.constant(‘12222211’)
sess=tf.Session()
print(sess.run(hello))

但运行出错,显示

AttributeError: module ‘tensorflow’ has no attribute ‘Session’

后来发现是因为现在是 Tensorflow2.x 版本,在运行 Session 语句时,需要执行下面语句

sess=tf.compat.v1.Session()

但是新的问题又来了,出错显示

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

找了很久,又有要重下tensorflow的,又有用keras的,但我感觉都很麻烦
最后发现只要在代码中加入下面一行

tf.compat.v1.disable_eager_execution()

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
hello=tf.constant(‘Hello!Tensorflow’)
sess=tf.compat.v1.Session()
print(sess.run(hello))

问题解决

原因探寻

在查阅了 Tensorflow 官方文档后,官方给出的该语句作用是

This function can only be called before any Graphs, Ops, or Tensors have been created. It can be used at the beginning of the program for complex migration projects from TensorFlow 1.x to 2.x.

即把 Tensorflow 1.x 的工作迁移至 2.x

  • 44
    点赞
  • 73
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值