tensorflow应用Session模块出现错误 AttributeError: module 'tensorflow' has no attribute 'Session' 错误解决

运行代码,引用模块错误:

with tf.Session() as sess:
    for i in range(num):

 

出现错误:

tensorflow应用Session模块出现错误 AttributeError: module 'tensorflow' has no attribute 'Session' 错误解决

出现这个错误的原因是,tensorflow 2.0版本将该模块移除,所以我们要借用tensorflow 1.0中的Session函数

网上找到一个解决方法还不错:

将原代码中开头的

import tensorflow as tf

改成:

import tensorflow.compat.v1 as tf 
tf.disable_v2_behavior()

 

tensorflow应用Session模块出现错误 AttributeError: module 'tensorflow' has no attribute 'Session' 错误解决

 

这样只需要改变头,后续不需要再变动,问题解决

 

tensorflow应用Session模块出现错误 AttributeError: module 'tensorflow' has no attribute 'Session' 错误解决