简体   繁体   中英

Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(135162, 6), dtype=float32) is not an element of this graph

I created a machine learning model using Keras for sentiment analysis and created a simple API using flask as shown in the code below. for the first prediction it works fine and gives an output in the results page, but when I try again it gives me the error above.

I've seen some similar questions and their solutions but these solutions did not work for me. I tried different ways to save and load the model created on keras as well but to no avail.

#creating instance of the class
app=Flask(__name__)

@app.route('/')
def welcome():
    return flask.render_template('welcome.html')

#prediction function
def ValuePredictor(to_predict):
    model = pickle.load(open("model.pkl","rb"))
    print("Loaded model from disk")
    result = model.predict(to_predict)
    tf.reset_default_graph()
    return result

@app.route('/result',methods = ['POST'])
def result():
    if request.method == 'POST':
        to_predict_list = request.form.to_dict()
        to_predict_list=list(to_predict_list.values())
        test_tokens = tokenizer_obj.texts_to_sequences(to_predict_list)
        test_pad = pad_sequences(test_tokens, maxlen = max_length, padding= 'post')
        print(test_pad)
        result = ValuePredictor(test_pad)
        return render_template("result.html",prediction=result)

if __name__ == '__main__':
   app.run(debug= True, port = 5000)

I expect to input text then receive a result in the results page then return back to the main page and input new text and get another result and so on.

Currently it works fine for the first time then gives the error above the times after that.

adding the following to the code solved it!

from keras import backend as K

 K.clear_session()

where I added this after the prediction as such:

def ValuePredictor(to_predict):
    model = pickle.load(open("model.pkl","rb"))
    print("Loaded model from disk")
    result = model.predict(to_predict)
    K.clear_session()
    return result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM