Flask與keras結合的幾個常見錯誤

1. ValueError: Tensor Tensor(“dense_1/Sigmoid:0”, shape=(?, 1), dtype=float32) is not an element of this graph.

在Flask中使用tensorflow的model,一在界面中調用 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()
    # 執行預測函數

但是我當時測試時又報了另一個bug,但是這個bug也不好解決,試了很多方法也沒解決,當然最終還是可以解決的,具體解決方式參考第三點。

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}}]]

後來經過N遍測試後找到了以下兩種解決方式,僅供參考:

方法一:在調用前加載model和graph,但是這樣會導致程序每次調用都需要重新加載model,然後運行速度就會很慢,不過這種修改方式是最簡單的。

graph = tf.get_default_graph()
    model = models.load_model('./static/my_model2.h5')
    with graph.as_default():
        result = model.predict(tokens_pad)

方法二:在創建model後,先使用一遍 model.predict(),參數的大小和真實大小一致,這個是真正解決之道,同時不影響使用速率。

# 使用前:
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…… 的錯誤即第二點,不過估摸着這個是個例,應該是程序問題。

2.RuntimeError: The Session graph is empty. Add operations to the graph before calling run().

graph = tf.get_default_graph()
    with graph.as_default():
        # 相關代碼
        # 本次測試中是需要把調用包含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結合使用時的常見錯誤,解決方式如下:

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

# 每次使用有關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

設置一下XLA_FLAGS指向你的cuda安裝目錄即可

os.environ["XLA_FLAGS"]="--xla_gpu_cuda_data_dir=/usr/local/cuda-10.0"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章