Tensorflow错误:AttributeError: module 'tensorflow' has no attribute 'Session'/ 'ConfigProto'

python在运行简单的Tensorflow代码时,出现以下错误:

AttributeError: module 'tensorflow' has no attribute 'Session'

AttributeError: module 'tensorflow' has no attribute 'ConfigProto'

源代码:

import tensorflow as tf
import os
os.environ["CUDA_VISIBLE_DEVICES"]="0"

hello = tf.constant('Hello, TensorFlow!')
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.9 # 占用GPU90%的显存
sess= tf.Session(config=config)
print(sess.run(hello))

错误原因:

Tensorflow两个不同的版本中对于函数的定义不同,两个版本函数定义对照可参考:

https://docs.google.com/spreadsheets/d/1FLFJLzg7WNP6JHODX5q8BDgptKafq_slHpnHVbJIteQ/edit#gid=0

网页打不开的话,可以参考博客:CSDN博主「Ooo。」的原创文章:https://blog.csdn.net/xue_csdn/article/details/102923926

该博客提供了百度网盘链接,如下,可以直接下载观看不同版本的参数介绍

https://pan.baidu.com/s/1cWHtdQM1yoMOM4ZXt_vY9w,提取码:i953 】

解决方法:

使用tf.compat.v1.XX()来进行代码替换

hello = tf.constant('Hello, TensorFlow!')
config = tf.compat.v1.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.9 # 占用GPU90%的显存
sess= tf.compat.v1.Session(config=config)

参考博客:https://blog.csdn.net/qq_33440324/article/details/94200046

但是上述方法,使用之后,又出现了新的问题:

AttributeError: module 'tensorflow' has no attribute 'Session'

解决上述问题的方法,见我的另一篇博客:【Tensorflow错误:RuntimeError: The Session graph is empty. Add operations to the graph before calling run()