如何为此机器学习模型设置request.py?

时间:2019-05-25 22:25:45

标签: python machine-learning flask deployment regression

我正在遵循此online tutorial并使用Python部署机器学习模型。我已经按照指示完成了所有部分,包括创建了model.py和request.py文件,并在Terminal中运行它们。

但是,我无法创建request.py文件来生成预测。我的server.py是:

# Import libraries
import numpy as np
import flask
import pickle

app = flask.Flask(__name__)

model = pickle.load(open("model.pkl","rb"))

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

    #our model rates the wine based on the input array
    prediction = model.predict([feature_array]).tolist()

    #preparing a response object and storing the model's predictions
    response = {}
    response['predictions'] = prediction

    #sending our response object back as json
    return flask.jsonify(response)

还有我的request.py:

import requests
# URL
url = 'http://localhost:5000/request'

r = requests.post(url,json=[7.4,0.66,0,1.8,0.075,13,40,0.9978,3.51,0.56,9.4])
print(r.json())

2 个答案:

答案 0 :(得分:1)

将此导入到server.py文件中:

from flask import request

在您的server.py文件末尾添加此文件(用于在端口5000和debug=True上运行服务器,以调试并解决错误,如果有的话):

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

更新后的request.py文件(您的代码缺少您在feature_array文件中引用的server.py键):

import requests, json
# URL
url = 'http://localhost:5000/predict'
r = requests.post(url, json={"feature_array":[7.4,0.66,0,1.8,0.075,13,40,0.9978,3.51,0.56,9.4]})
print(r.json())

在运行server.py文件之前运行request.py

答案 1 :(得分:0)

您的server.py文件是否缺少本教程第2行所示的from flask import request吗?