首页 文章

TensorFlow,Keras,Flask - 无法通过烧瓶运行我的keras模型作为web应用程序

提问于
浏览
1

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

app.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后端会有帮助吗?

任何帮助将受到高度赞赏 . 这是我的大学项目,提交日期已经过去 . 请帮忙 . 提前致谢 .

2 回答

  • 6

    我遇到了同样的问题,发现其中一个可能的解决方案是明确指定图形 . 请注意,这是特定于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)
    
        ...
    
  • 1

    问题解决了 . 改变keras后端到theano做了伎俩 . 可以通过keras目录中的keras.json文件更改Theano后端 .

相关问题