安裝好tensorflow2.0之后,當使用Session時,報錯AttributeError: module 'tensorflow' has no attribute 'Session':
源代碼:
import tensorflow as tf import os os.environ["CUDA_VISIBLE_DEVICES"]="0" a=tf.constant(2) b=tf.constant(3) with tf.Session() as sess: print("a:%i" % sess.run(a),"b:%i" % sess.run(b)) print("Addition with constants: %i" % sess.run(a+b)) print("Multiplication with constant:%i" % sess.run(a*b))
錯誤信息:
錯誤的意思是tensortflow模塊沒有Session屬性,后來查閱資料發現,tensorflow2.0版本中的確沒有Session這個屬性,如果安裝的是tensorflow2.0版本又想利用Session屬性,可以將tf.Session()更改為:
tf.compat.v1.Session()
這個方法可以解決此類問題,不僅僅適用於Session屬性。
再次運行時,程序又報了另一個錯誤:
查閱資料發現,原因是2.0與1.0版本不兼容,在程序開始部分添加以下代碼:
tf.compat.v1.disable_eager_execution()
就可以正常運行了。
tensorflow的官網對disable_eager_execution()方法是這樣解釋的:
This function can only be called before any Graphs, Ops, or Tensors have been created. <br>It can be used at the beginning of the program for complex migration projects from TensorFlow 1.x to 2.x.
翻譯過來為:此函數只能在創建任何圖、運算或張量之前調用。它可以用於從TensorFlow 1.x到2.x的復雜遷移項目的程序開頭。