升級到Tensorflow 2.0 踩坑


升級到Tensorflow 2.0 踩坑

https://blog.csdn.net/javastart/article/details/102525102

Tensorflow 2.0發布已經有一段時間了,各種基於新API的教程看上去的確簡單易用,一個簡單的mnist手寫識別只需要下面不到20行代碼就OK了,

   

import tensorflow as tf

mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(512, activation=tf.nn.relu), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation=tf.nn.softmax)])model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5)model.evaluate(x_test, y_test)

   

於是我一激動,直接更新到了最新版本,直接執行

  •    

pip installupgrade tensorflow-gpu

完成更新,打開以前寫的程序,然后我就悲劇了。不管是簡單的還是復雜的代碼演示,驚訝的發現沒有一個可以跑的,最后發現我以前寫的tensorflow+Kears教程居然可以跑,結果一跑一個更大的悲劇等着我,直接跟我說CUDA版本不是10.0的版本,版本太低。於是我就認真重新看了tensorflow2.0的版本release說明,發現這么一句話:

Many APIs are either gone or moved in TF 2.0. Some of the major changes include removing tf.app, tf.flags, and tf.logging in favor of the now open-source absl-py, rehoming projects that lived in tf.contrib, and cleaning up the main tf.* namespace by moving lesser used functions into subpackages like tf.math.

我終於對這段話有了很深刻與痛苦的領悟。是真的該刪的刪,該移的移!該拋棄的拋棄、完全沒有考慮到開發者的切身感受。

 當你開始運行程序時候,一般會順序給你下面幾個驚喜!

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

 還有沒有天理了,這些不是在tensorflow1.x中必須的嗎,怎么說沒就沒有了,告訴你是真的沒有,在tensorflow2.0中,如果還想讓它有怎么辦?

 用tf.compat.v1.xxxx上面的那些no attribute錯誤就會解決了。舉例

​​​​​​​tf.Session()改為tf.compat.v1.Session()

然后我很高興的去繼續運行程序,就發現一個大BUG在等我

tensorflow.python.framework.errors_impl.internalerror: cudagetdevice() failed. status: cudageterrorstring symbol not found.

 原因:

找不到cudart64_100.dll,這個是CUDA10.0的,我之前安裝的是CUDA9.0,tensorflow2.0不支持了,所以這個必須換,怎么辦,一頓卸載安裝+配置猛如虎,我終於全部搞定了。在windows10系統下面 Tensorflow 2.0 + VS2015 + CUDA10.0 終於工作了,這個我只是改好了第一個代碼,這樣改下去,什么時候才完,別擔心,后來我又發現了tensorflow官方提供的另外一個神器,可以幫助它代碼自動的從v1版本轉換到v2版本,可能連tensorflow官方自己也不好意思它跨度這么大的版本更新,所以還算提供了一個貼心的工具。直接cmd之后在命令行運行即可實現代碼的自動轉換:

 如果你完全不想改動v1版本的代碼,怎么辦,這么操作即可:​​​​​​​

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

親測好用!

 


免責聲明!

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



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