python - 加载 keras 模型并将其缓存在变量中,而无需重新加载
问题描述
在我的 Flask 应用程序开始时加载模型,然后在我的端点中使用它进行预测会导致错误
'ValueError: Tensor Tensor("dense/Softmax:0", shape=(?, 4), dtype=float32) 不是该图的元素。'
model = keras.models.load_model("model.h5")
@app.route("/predict", methods=["POST"])
def predict():
json_data = request.get_json()
variable = preparePredictionInput(
[variable], alphabetDict, maxVariableLength)
prediction = list(model.predict(variable, steps=1, verbose=1)[0])
但是每次调用预测端点时加载 keras 模型似乎工作得很好
@app.route("/predict", methods=["POST"])
def predict():
json_data = request.get_json()
model = keras.models.load_model("model.h5")
variable = preparePredictionInput(
[variable], alphabetDict, maxVariableLength)
prediction = list(model.predict(variable, steps=1, verbose=1)[0])
有没有办法来解决这个问题?这从根本上降低了每次都必须重新加载模型的性能。
解决方案
似乎您的模型变量不是全局的。看看下面的代码:
def init():
global model
model = lkeras.models.load_model("model.h5")
@app.route("/predict", methods=["POST"])
def predict():
json_data = request.get_json()
variable = preparePredictionInput([variable], alphabetDict, maxVariableLength)
prediction = list(model.predict(variable, steps=1, verbose=1)[0])
if __name__ == "__main__":
init()
app.run()
推荐阅读
- r - 如何在函数中定义可选参数
- django - 无法使用 Minikube + ingress + Django 路由流量
- racket - 球拍 - 定义结构和抽象列表功能
- google-apps-script - 是否可以更新现有的数据验证帮助文本?
- json - 在逻辑应用程序 JSON 数组中解析单个对象的抛出错误但对于多个对象它工作正常
- json - 'Int' 不能转换为 'CGFloat' SwiftUI 误导性错误
- android - 我很困惑android中的ffmpeg文件是什么
- python - 处理pandas groupby中的项目很慢?我们应该使用哈希图吗?
- java - JavaFX中如何让TableView根据其内容自动改变高度?
- python - Discord.py 检查 Channel 是否为 DM