tensorflow使用Session模塊時報錯:AttributeError: module 'tensorflow' has no attribute 'Session',已解決


安裝好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. 
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的復雜遷移項目的程序開頭。

更新:

找到了一個更簡單的方法,在引用tensorflow時,直接用:

import tensorflow.compat.v1 as tf

一勞永逸的方法。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM