AttibuteError: module ‘tensorflow’ has no attribute ‘get_default_graph’.

在终端中输入 python train.py 运行 train.py 文件。
出现报错:AttibuteError: module ‘tensorflow’ has no attribute ‘get_default_graph’.

该报错的意思是:tensorflow模块没有get_default_graph属性。

这是由于Keras API(https://keras.io/)有多个实现,包括原始和参考实现(https://github.com/keras-team/keras),还有各种其他实现,包括tf.keras,它是TensorFlow的一部分。
由于TensorFlow 2默认为急切执行,TF2中集成了keras,因此Keras需要进行一些更改才能与之兼容。

解决方法

from tensorflow import keras
而不是直接使用:import keras
from tensorflow.keras import layers 
而不是使用 from keras import layers

如果不同代码文件之间有相互嵌套,只修改当前python文件可能还是会出现同样的报错信息:
AttibuteError: module ‘tensorflow’ has no attribute ‘get_default_graph’.

此时可以直接看代码找到嵌套的文件进行修改。
也可以先卸载原来的keras包查看哪里还有问题。
在终端中输入

pip uninstall keras

出现报错信息:ModuleNotFoundError: no module named ‘keras’
留意详细报错信息中 Keras 出现的具体文件和对应的位置,逐个进行修改。
如下图就是在segnet.py中还有没有修改成tensorflow.keras的地方。
在这里插入图片描述
修改完成后保存,再运行就不会再报错了。

参考文章:https://blog.csdn.net/edward_zcl/article/details/103488191

你可能感兴趣的:(深度学习,python,深度学习,pytorch,python,tensorflow,人工智能)