天天看點

FastAPI+TensorFlow1.14常見錯誤

背景:

在用keras/tensorflow訓練好模型後,使用fastAPI部署服務時的兩個常見錯誤

錯誤1:

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

錯誤2:

tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized val

解決方法:

from tensorflow.python.keras.backend import set_session
# 解決問題1
sess = tf.Session()
graph = tf.get_default_graph()
# tf2: graph = tf.compat.v1.get_default_graph()
# 解決問題2
set_session(sess)
model = models.load_model(model_path)
# 每次使用有關模型請求時
# for each request:
global sess
global graph
with graph.as_default():
    set_session(sess)
    model.predict(...)
           

繼續閱讀