Keras多線程機制與flask多線程沖突的解決方案
在使用flask部署Keras,tensorflow等框架時候,經(jīng)常出現(xiàn)
FailedPreconditionError: Attempting to use uninitialized value batchnormalization_
或者
Tensor Tensor("crf_1/cond/Merge:0", shape=(?, ?, 260), dtype=float32) is not an element of this graph.
使用keras.backend.clear_session()可能會導(dǎo)致前后兩處預(yù)測結(jié)果不一樣,因為圖發(fā)生了變化。以下是解決方案。
graph = tf.get_default_graph()
sess = tf.Session(graph=graph)
def modelpredict(content):
#keras.backend.clear_session()
global graph
global sess
with sess.as_default():
with graph.as_default():
keras.model.predict()
補充:Flask與keras結(jié)合的幾個常見錯誤
1、 ValueError: Tensor Tensor(“dense_1/Sigmoid:0”, shape=(?, 1), dtype=float32) is not an element of this graph.
在Flask中使用tensorflow的model,一在界面中調(diào)用 model.predict() 就報下面這個錯誤,不過在單獨的 .py 文件中使用卻不報錯。
ValueError: Tensor Tensor("dense_1/Sigmoid:0", shape=(?, 1), dtype=float32) is not an element of this graph.
添加如下代碼可以解決:
import tensorflow as tf
graph = tf.get_default_graph()
model = models.load_model(…………)
# 使用處添加:
global graph
global model
with graph.as_default():
model.predict()
# 執(zhí)行預(yù)測函數(shù)
但是我當(dāng)時測試時又報了另一個bug,但是這個bug也不好解決,試了很多方法也沒解決,當(dāng)然最終還是可以解決的,具體解決方式參考第三點。
tensorflow.python.framework.errors_impl.FailedPreconditionError: Error while reading resource variable dense_1/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Resource localhost/dense_1/bias/class tensorflow::Var does not exist.
[[{{node dense_1/BiasAdd/ReadVariableOp}}]]
后來經(jīng)過N遍測試后找到了以下兩種解決方式,僅供參考:
方法一:
在調(diào)用前加載model和graph,但是這樣會導(dǎo)致程序每次調(diào)用都需要重新加載model,然后運行速度就會很慢,不過這種修改方式是最簡單的。
graph = tf.get_default_graph()
model = models.load_model('./static/my_model2.h5')
with graph.as_default():
result = model.predict(tokens_pad)
方法二:
在創(chuàng)建model后,先使用一遍 model.predict(),參數(shù)的大小和真實大小一致,這個是真正解決之道,同時不影響使用速率。
# 使用前:
model = models.load_model('./static/my_model2.h5')
# a 矩陣大小和 tokens_pad 一致
a = np.ones((1, 220))
model.predict(a)
# 使用時:
global model
result = model.predict(tokens_pad)
但是在使用后又遇到了 The Session graph is empty…… 的錯誤即第二點,不過估摸著這個是個例,應(yīng)該是程序問題。
2、RuntimeError: The Session graph is empty. Add operations to the graph before calling run().
graph = tf.get_default_graph()
with graph.as_default():
# 相關(guān)代碼
# 本次測試中是需要把調(diào)用包含model.predict()方法的方法的代碼放到這里
3、tensorflow.python.framework.errors_impl.FailedPreconditionError: Error while reading resource variable dense_1/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Resource localhost/dense_1/bias/class tensorflow::Var does not exist.[[{{node dense_1/BiasAdd/ReadVariableOp}}]]
這個錯誤呢,也是TensorFlow和Flask結(jié)合使用時的常見錯誤,解決方式如下:
from tensorflow.python.keras.backend import set_session
# 程序開始時聲明
sess = tf.Session()
graph = tf.get_default_graph()
# 在model加載前添加set_session
set_session(sess)
model = models.load_model(…………)
# 每次使用有關(guān)TensorFlow的請求時
# in each request (i.e. in each thread):
global sess
global graph
with graph.as_default():
set_session(sess)
model.predict(...)
————————————————
4、 Can't find libdevice directory ${CUDA_DIR}/nvvm/libdevice. This may result in compilation or runtime failures, if the program we try to run uses routines from libdevice
設(shè)置一下XLA_FLAGS指向你的cuda安裝目錄即可
os.environ["XLA_FLAGS"]="--xla_gpu_cuda_data_dir=/usr/local/cuda-10.0"
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
pandas中按行或列的值對數(shù)據(jù)排序的實現(xiàn)
本文主要介紹了pandas中按行或列的值對數(shù)據(jù)排序的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
Python中常用數(shù)據(jù)類型使用示例概括總結(jié)
這篇文章主要為大家介紹了Python中常用數(shù)據(jù)類型使用示例概括總結(jié),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04
Python2和Python3之間的str處理方式導(dǎo)致亂碼的講解
今天小編就為大家分享一篇關(guān)于Python2和Python3之間的str處理方式導(dǎo)致亂碼的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-01-01
Python中實現(xiàn)地圖可視化的方法小結(jié)
Python提供了多個強大的庫,如Folium、Matplotlib、Geopandas等,使得創(chuàng)建漂亮而具有信息量的地圖變得簡單而靈活,本文將詳細介紹如何使用這些庫繪制漂亮的地圖,感興趣的可以了解下2023-12-12
Python數(shù)據(jù)類型之String字符串實例詳解
這篇文章主要介紹了Python數(shù)據(jù)類型之String字符串,結(jié)合實例形式詳細講解了Python字符串的概念、定義、連接、格式化、轉(zhuǎn)換、查找、截取、判斷等常見操作技巧,需要的朋友可以參考下2019-05-05

