首页 > 解决方案 > flask + restful web service 无法运行文本分类模型 + python

问题描述

用于创建 restful api web 服务的代码

import numpy as np
import pandas as pd
#need to "conda install flask" for this to work
from flask import Flask, abort, jsonify, request
import pickle

Text_classification_model = pickle.load(open(r"D:\Sentiment_Analysis_Project\Deb\Sentiment_Analysis\Linear_SVC_TEXT_CLASSI_Final_82per_Model.pkl", "rb"))

app = Flask(__name__)

#@app.route("/")
#def hello():
#    return "Hello"

@app.route("/")
def make_predict():
    #all kinds of error checking should go here
    data = request.get_json(force=True)
    #convert our json to a numpy array
    predict_request = data['Clean_Text_Body']
    predict_request = np.array[predict_request]

    #np.array goes in to Linear SVC model, prediction comes out
    y_hat = Text_classification_model.predict(predict_request)

    #return our prediction
    output = [y_hat[0]]
    return jsonify(results=output)

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

当它被称为 .py 文件时,它会正确执行并正确显示“ http://localhost:5000/ ”作为 url。

稍后当我尝试使用以下代码将数据发布到模型中时,

import json
import requests

url = "http://localhost:8082/"
data = json.dumps({'Clean_Text_Body':"the product was amazing i just love it"})
headers = {'accept-language': 'en', 'content-type': 'application/json'}
r = requests.post(url, data = data, headers=headers)
Output = json.loads(r.text)['Output'] ##error section
# o/p is string eg: "4"
print("results == ", Output)

它给出了以下错误

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python\Anaconda\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Python\Anaconda\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python\Anaconda\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

使用的模型是用于情感分类的线性 SVC 模型,该模型在具有“正面”和“负面”两个级别的文本上进行训练

该模型预测文本/字符串是否具有正面或负面情绪。

标签: pythonmachine-learningdeploymentmodelflask-restful

解决方案


您使用了错误的请求功能!

你想使用这个:http ://docs.python-requests.org/en/master/

不是烧瓶请求对象!您不需要from flask import Flask,request,jsonify在第二个脚本中使用 !

你需要使用import requests

接着requests.post()


推荐阅读