首页 > 解决方案 > Keras 烧瓶 API 没有给我输出

问题描述

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

我从这里得到了代码示例并即兴创作以满足我的需要

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"}

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

编辑:我删除了预测函数中的异常tryblock下面是预测函数的样子

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 中发布整个错误消息,因为我的问题中的大部分块似乎都是代码。

谢谢!!

标签: apiflaskkeraspython-3.6

解决方案


现在这是我的猜测。在使用 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)})

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


推荐阅读