Keras flask API没有给我输出

时间:2018-05-28 12:55:21

标签: api flask keras python-3.6

我对烧瓶很新。我在Python3的Keras中使用CNN模型开发了一个文档分类模型。下面是我在Windows机器中用于app.py文件的代码。

我从here获得了代码示例,并根据我的需要对其进行了即兴创作

import os
from flask import jsonify
from flask import request
from flask import Flask
import numpy as np
from keras.models import model_from_json
from keras.models import load_model
from keras.preprocessing.text import Tokenizer, text_to_word_sequence
from keras.preprocessing.sequence import pad_sequences


#star Flask application
app = Flask(__name__)

path = 'C:/Users/user/Model/'
json_file = open(path+'/model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
keras_model_loaded = model_from_json(loaded_model_json)
keras_model_loaded.load_weights(path+'/model.h5')
print('Model loaded...')

def preprocess_text(text,num_max = 1000,max_review_length = 100):
    tok = Tokenizer(num_words=num_max)
    tok.fit_on_texts(texts)
    cnn_texts_seq = tok.texts_to_sequences(texts)
    cnn_texts_mat = sequence.pad_sequences(cnn_texts_seq,maxlen=max_review_length)
    return cnn_texts_mat

# URL that we'll use to make predictions using get and post
@app.route('/predict',methods=['GET','POST'])

def predict():
    try:
        text = request.args.get('text')
        x = preprocess_text(text)
        y = int(np.round(keras_model_loaded.predict(x)))
        #print(y)
        return jsonify({'prediction': str(y)})
    except:
        response = jsonify({'error': 'problem predicting'})
        response.status_code = 400
        return response


if __name__ == "__main__":
    port = int(os.environ.get('PORT', 5000))
    # Run locally
    app.run(host='0.0.0.0', port=port)

在我的Windows机器中,我导航到控制台中保存app.py文件的路径并执行命令py -3.6 app.py

当我转到网址http://localhost:5000/predict并输入浏览器

http://localhost:5000/predict?text=I've had my Fire HD 8 two weeks now and I love it. This tablet is a great value. We are Prime Members and that is where this tablet SHINES.

它没有给我任何类作为输出,而是我得到它作为输出{"error":"problem predicting"}

有关如何解决此问题的任何帮助?

修改:我删除了预测函数中除try以外的block。以下是预测函数的样子

def predict():
    text = request.args.get('text')
    x = preprocess_text(text)
    y = int(np.round(keras_model_loaded.predict(x)))
    return jsonify({'prediction': str(y)})

现在我变得异常了。错误信息是

[2018-05-28 18:33:59,008] ERROR in app: Exception on /predict [GET]
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\_compat.py", line 35, in reraise
    raise value
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "app.py", line 59, in predict
    x = preprocess_text(text)
  File "app.py", line 37, in preprocess_text
    tok.fit_on_texts(texts)
NameError: name 'texts' is not defined
127.0.0.1 - - [28/May/2018 18:33:59] "GET /predict?text=I%27ve%20had%20my%20Fire%20HD%208%20two%20weeks%20now%20and%20I%20love%20it.%20This%20tablet%20is%20a%20great%20value.%20We%20are%20Prime%20Members%20and%20that%20is%20where%20this%20tablet%20SHINES. HTTP/1.1" 500 -

Edit2:我已编辑代码

def preprocess_text(texts,num_max = 1000,max_review_length = 100):
    tok = Tokenizer(num_words=num_max)
    tok.fit_on_texts(texts)
    cnn_texts_seq = tok.texts_to_sequences(texts)
    cnn_texts_mat = pad_sequences(cnn_texts_seq,maxlen=max_review_length)
    return cnn_texts_mat

# URL that we'll use to make predictions using get and post
@app.route('/predict',methods=['GET','POST'])

def predict():
    text = request.args.get('text')
    x = preprocess_text(text)
    y = keras_model_loaded.predict(x)
    return jsonify({'prediction': str(y)})

现在错误信息是

packages\tensorflow\python\framework\ops.py", line 3402, in _as_graph_element_locked raise ValueError("Tensor %s is not an element of this graph." % obj) ValueError: Tensor Tensor("output/Sigmoid:0", shape=(?, 1), dtype=float32) is not an element of this graph. 127.0.0.1 - - [28/May/2018 19:39:11] "GET /predict?text=I%27ve%20had%20my%20Fire%20HD%208%20two%20weeks%20now%20and%20I%20love%20it.%20This%20tablet%20is%20a%20great%20value.%20We%20are%20Prime%20Members%20and%20that%20is%20where%20this%20tablet%20SHINES. HTTP/1.1" 500 -

我无法理解并调试此错误。不确定这意味着什么。任何人都可以帮助我理解这个错误并为此提出解决方案吗?

此外,我无法在stackoverflow中发布整个错误消息,因为我的问题中的大部分块似乎都是代码。

谢谢!

1 个答案:

答案 0 :(得分:1)

现在我猜对了。使用Flask和Tensorflow的交叉线程时出现问题。这是一个修复它:

import tensorflow as tf
# ...
graph = tf.get_default_graph()
def predict():
  text = request.args.get('text')
  x = preprocess_text(text)
  with graph.as_default():
    y = int(np.round(keras_model_loaded.predict(x)))
  return jsonify({'prediction': str(y)})

通过包装预测来强制使用默认图形。