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()】
