python - 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 模型,该模型在具有“正面”和“负面”两个级别的文本上进行训练
该模型预测文本/字符串是否具有正面或负面情绪。
解决方案
您使用了错误的请求功能!
你想使用这个:http ://docs.python-requests.org/en/master/
不是烧瓶请求对象!您不需要from flask import Flask,request,jsonify
在第二个脚本中使用 !
你需要使用import requests
接着requests.post()
推荐阅读
- javascript - 对于 React 中的 HOC 是否不鼓励这样做?
- laravel - 如果在密码重置期间未注册电子邮件,则 Laravel 错误消息(从 5.6 升级到 5.7)
- c# - 如何禁用通过 RDP(终端服务)运行的应用程序的多个实例?
- visual-studio - 尝试使用 .docx 文件进行合并时出错
- firebase - Firebase:为什么将 Firestore .onSnapshot 分配给变量?
- excel - Power BI 水平运行总计
- apache-kafka - Kafka 中的主题数量限制
- python - Pandas 中时间序列数据的格式问题和缩写数据条目
- python - Spark 找不到 Python 模块
- css - 如何设置自动适应(或自动填充)行之间的间隙?