解决:AttributeError: module ‘tensorflow.keras.backend‘ has no attribute ‘get_session‘

问题:将tensorflow 1代码迁移到tensorflow 2版本时出现错误,环境为tensorflow 2.3

AttributeError: module ‘tensorflow.keras.backend‘ has no attribute ‘get_session‘ 

分析:出错原因是因为tensorflow 2中tensorflow.keras.backend没有get_session接口,但是其提供了兼容tensorflow 1的接口,也即 tensorflow.compat.v1.keras.backend中是有get_session接口的。

解决方案:使用tensorflow.compat.v1代替tensorflow,例如

import tensorflow.compat.v1 as tf
# 此时可以正常使用get_session
tf.keras.backend.get_session()

# 或直接导入
from tensorflow.compat.v1.keras.backend import get_session

延伸

tensorflow提供了兼容接口,例如兼容tf1的 tensorflow.compat.v1和兼容tf2的tensorflow.compat.v2

在tf1向tf2迁移中有诸多问题,部分通过兼容接口可以解决,而部分则需要用全新接口改写代码,遇到迁移问题时解决思路可以参考:解决tensorflow 1 迁移到tensorflow 2中AttributeError类问题的思路_豆芽菜-CSDN博客

参考:解决tensorflow报错:AttributeError: module ‘tensorflow.keras.backend‘ has no attribute ‘get_session‘ 问题_星空-CSDN博客

猜你喜欢

转载自blog.csdn.net/dou3516/article/details/120078449
今日推荐