使用python将参数传递给Flask中的模型

时间:2018-11-01 13:20:50

标签: python flask sklearn-pandas

我有一个训练有素的模型,已将其导出为泡菜文件。我正在尝试在flask上运行的python文件中使用pickle文件。但是,由于文件出错,我无法传递参数。当我在jupyter笔记本中使用相同的代码时,将传递参数并给出预测。但是,在烧瓶上运行它时,会出现以下错误:

Traceback (most recent call last):


File "C:\model1\venv\lib\site-packages\flask\app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\model1\venv\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\model1\venv\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\model1\venv\lib\site-packages\flask\_compat.py", line 35, in reraise
    raise value
  File "C:\model1\venv\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\model1\venv\lib\site-packages\flask\app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\model1\hello.py", line 26, in predict
    model = pickle.load(open("prediction.pkl","rb"))
  File "sklearn\neighbors\binary_tree.pxi", line 1152, in sklearn.neighbors.kd_tree.BinaryTree.__setstate__
  File "sklearn\neighbors\binary_tree.pxi", line 235, in sklearn.neighbors.kd_tree.get_memview_ITYPE_1D
ValueError: Buffer dtype mismatch, expected 'ITYPE_t' but got 'long long'

我的 hello.py 文件如下:

import pickle
import numpy as numpy
from decimal import Decimal
from flask import Flask, request, json

from sklearn.externals import joblib

app = Flask(__name__)

@app.route('/predict', methods=['POST'])
def predict():
    print(request.form)
    features = request.form["features"]

    features = json.loads(features)

    features = numpy.array(features)

    features = features.reshape(1, -1)
    model = pickle.load(open("prediction.pkl","rb"))

    prediction = model.predict(features).tolist()
    print(features)
    print(prediction)
    return json.dumps({"Prediction":prediction})

if __name__ == '__main__':
    app.run(host='127.0.0.1')

谁能建议解决错误的方法?

1 个答案:

答案 0 :(得分:0)

嗨,我认为您的模型已在不同的sklearn库版本上进行了训练,而加载模型sklearn库在不同版本上进行了训练。或python版本问题。