从烧瓶中得到结果

时间:2020-05-23 14:28:41

标签: python machine-learning flask keras deep-learning

我已经用keras训练了一个深度学习模型(lstm),并用h5保存了它,现在我想“点击”一个Web服务以便找回一个类别。这是我第一次尝试这样做,所以我有些困惑。我不知道该如何归类。同样,当我向http://localhost:8000/predict发送请求时,也会收到以下错误消息,

The server encountered an internal error and was unable to complete your 
request. Either the server is overloaded or there is an error in the 
application.

和笔记本电脑

ValueError: Tensor Tensor("dense_3/Softmax:0", shape=(?, 6), dtype=float32) 
is not an element of this graph.

我尝试了enter link description here的解决方案,但没有用

到目前为止的代码如下

from flask import Flask,request, jsonify#--jsonify will return the data
import os
from keras.models import load_model

app = Flask(__name__)

model=load_model('lstm-final-five-Copy1.h5')

@app.route('/predict', methods= ["GET","POST"])
def predict():
    df_final = pd.read_csv('flask.csv')

    activities = df_final['activity'].value_counts().index

    label = LabelEncoder()
    df_final['label'] = label.fit_transform(df_final['activity'])

    X = df_final[['accx', 'accy', 'accz', 'gyrx', 'gyry', 'gyrz']] 
    y = df_final['label'] 

    scaler = StandardScaler()
    X = scaler.fit_transform(X)

    df_final = pd.DataFrame(X, columns = ['accx', 'accy', 'accz', 'gyrx', 
    'gyry', 'gyrz'])
    df_final['label'] = y.values

    Fs = 50
    frame_size = Fs*2 # 200 samples
    hop_size = frame_size # 40 samples
    def get_frames(df_final, frame_size, hop_size):

       N_FEATURES = 6 #x,y,z (acc,gut)

      frames = []
      labels = []
      for i in range(0, len(df_final) - frame_size, hop_size):
          accx = df_final['accx'].values[i: i + frame_size]
          accy = df_final['accy'].values[i: i + frame_size]
          accz = df_final['accz'].values[i: i + frame_size]
          gyrx = df_final['gyrx'].values[i: i + frame_size]
          gyry = df_final['gyry'].values[i: i + frame_size]
          gyrz = df_final['gyrz'].values[i: i + frame_size]

          # Retrieve the most often used label in this segment
          label = stats.mode(df_final['label'][i: i + frame_size])[0][0]
          frames.append([accx, accy, accz, gyrx, gyry, gyrz])
          labels.append(label)

      # Bring the segments into a better shape
      frames = np.asarray(frames).reshape(-1, frame_size, N_FEATURES)
      labels = np.asarray(labels)

      return frames, labels

    X, y = get_frames(df_final, frame_size, hop_size)

    pred = model.predict_classes(X)
    return jsonify({"Prediction": pred}), 201

if __name__ == '__main__':
app.run(host="localhost", port=8000, debug=False)

2 个答案:

答案 0 :(得分:1)

似乎在您的'/ predict' POST 端点中,您没有返回任何值,这就是为什么您没有按预期返回类别的原因。

如果您想添加 GET 方法,则可以添加如下所述的内容,

@app.route('/', methods=['GET'])
def check_server_status():
   return ("Server Running!")

POST 方法中,您可以在端点中返回预测,

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

    # Add in other steps here

    pred = model.predict_classes(X)
    return jsonify({"Prediction": pred}), 201

答案 1 :(得分:0)

据我所知,如果您没有安装熊猫,请执行pip install pandas并将其导入为import pandas as pd 您也可以在/prediction端点中添加“ GET”方法,例如:

@app.route("/predict", methods=["GET", "POST"])
相关问题