python - TensorFlow、Keras、Flask - 无法通过 Flask 将我的 Keras 模型作为 Web 应用程序运行

标签 python tensorflow flask keras tensor

我最近一直在为我的大学项目研究机器学习模型,该模型接受用户的健康因素并将其提供给 CNN,然后 CNN 会告诉用户他们在未来几年患糖尿病的时间。我已经写了一个keras模型并保存为hdf5格式。我已经检查过它在本地运行,保存的模型可以做出很好的预测。我想通过 Web 应用程序运行这个模型,因此过去几天我一直在研究 Flask。我已经为 flask app.py 和 index.html 编写了代码

应用.py

from flask import Flask, render_template, request
from flask import request
import numpy as np
from keras.models import load_model
from sklearn.preprocessing import MinMaxScaler
from flask import jsonify
import os
import re
import sys

# init model directory
MODEL_DIR = './models'
result=''

#init Flask
app = Flask(__name__)

#load the compiled model.
print("Loading model")
model = load_model(os.path.join(MODEL_DIR, 'classifier_model.hdf5'))

scaler= MinMaxScaler(feature_range=(0,1))

#routing for home page
@app.route('/', methods=['GET','POST'])
def index():
if request.method == 'GET':
    return render_template('index.html')

if request.method == 'POST':
    weight=float(request.form['weight'])
    height=float(request.form['height'])
    gluc=float(request.form['glucose')])
    bp=float(request.form['bp'])
    age=float(request.form['age'])
    height=height/100
    bmi=weight/(height*height)
    predict_data=np.array([[gluc, bp, bmi, age],[103,80,19.4,22]])
    scaled_predict_data=scaler.fit_transform((predict_data))
    round_predict = 
model.predict_classes(scaled_predict_data,verbose=0)
    res=np.array_str(round_predict[0])

    return render_template('index.html', value=res)





if __name__ == '__main__':
    port= int(os.environ.get('PORT',8080))
    app.run(host='0.0.0.0', port=port,debug=True)

index.html

<html>
<head>
    <script >
      var value= {{value}}
    </script>

</head>>
<body>

  <form  method = "POST">
     <p>Weight <input type = "number" name = "weight" /></p>
     <p>Height(CM) <input type = "number" name = "height" /></p>
     <p>Glucose(mg/dL) <input type = "number" name = "glucose" /></p>
     <p>Blood Pressure <input type ="number" name = "bp" /></p>
     <p>Age <input type ="number" name = "age" /></p>
     <p><input type = "submit" value = "submit" /></p><br>
     Output: {{ value }}<br>
  </form>

 </body>
</html>

现在,当我运行 app.py 代码时,一切正常,index.html 已呈现,但是当我点击提交按钮时,我收到此错误消息: ValueError: Tensor Tensor("dense_3/Sigmoid:0", shape=(?, 1), dtype=float32) 不是该图的元素。

切换到 theano 后端会有帮助吗?

任何帮助将不胜感激。这是我的大学项目,提交日期已经过去。请帮忙。提前致谢。

最佳答案

我遇到了同样的问题,发现一种可能的解决方案是明确指定图形。请注意,这是特定于 TensorFlow 的解决方案,因此不太便携。

import tensorflow as tf

...

g = tf.Graph()
with g.as_default():
    print("Loading model")
    model = load_model(os.path.join(MODEL_DIR, 'classifier_model.hdf5'))

...

@app.route('/', methods=['GET','POST'])
def index():
    ...

    with g.as_default():
        round_predict = model.predict_classes(scaled_predict_data,verbose=0)

    ...

关于python - TensorFlow、Keras、Flask - 无法通过 Flask 将我的 Keras 模型作为 Web 应用程序运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49018861/

相关文章:

python - tf.data.数据集 : How do I assign shape to a dataset (with shape undefined) that is guaranteed to output certain shape?

python - SQLAlchemy - 使用 DateTime 列查询以按月/日/年过滤

python - Flask:单元测试时,request.authorization 始终为 None

python - 更新挂起代码——Python MySQL Connector

python - 需要在 python 中获取迭代器的其余部分

python - 由于 AttributeError : 'module' object has no attribute 'datasets' ,Tensorflow 示例全部失败

mysql - 当带有 Flask-SQLAlchemy 的 Flask 应用程序正在运行时,如何同时在同一个数据库上使用 MySQL 客户端?

python - 是否可以将 TransformedTargetRegressor 添加到 scikit-learn 管道中?

python - 我怎样才能加速这个数据帧?

python - 是否有明确定义的 next_batch 函数?