问题与解决
今天根据 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