flask 一个轻量级的web框架
flask.ext.restful 快速生成restful api
numpy 数值计算包
pickle 用来保存模型
sklearn 用来建模
只需要四个步骤:
步骤1:建立模型
步骤2:模型写入pickle文件
步骤3:构建一个基于flask的API
步骤4:通过API调用模型
第一步是用sklearn建模。
from sklearn.tree import DecisionTreeClassifier
import pandas as pd
from pickle import dump
df = pd.read_csv('iris.csv')
X = df.ix[:,:4].values
y = df.ix[:,4].values
model = DecisionTreeClassifier()
model.fit(X,y)
第二步是将模型写入到pickle文件中
dump(model, open('model.pickle','wb'))
第三步是构建一个API,写一个server.py文件
from flask import Flask, request
from flask.ext.restful import Resource, Api
import pandas as pd
from pickle import load
app = Flask(__name__)
api = Api(app)
model = load(open('model.pickle','rb'))
class Model(Resource):
def post(self):
res = pd.DataFrame(request.json,index=[0]) # df
res = model.predict(res) # array
res = res.tolist()[0] # str
res = {'Species':res} # dict
return res
api.add_resource(Model, '/
if __name__ == '__main__':
app.run(debug=True)
保存好py文件后启用它。
python server.py
API会在如下地址监听
Running on http://127.0.0.1:5000/
第四步是调用这个API。另开一个终端,输入
curl -H "Content-type: application/json" -X POST http://127.0.0.1:5000/ -d '{"Sepal_Length":4.9,"Sepal_Width":3,"Petal_Length":1.4,"Petal_Width":0.2}'
{
"Species": "virginica"
}
也可以在python中实验。from requests import post
import json
url = 'http://127.0.0.1:5000'
data = '{"Sepal_Width": 3, "Petal_Width": 0.2, "Sepal_Length": 4.9, "Petal_Length": 1.4}'
headers = {'content-type':'application/json'}
post(url, data=json.dumps(data), headers=headers).json()
上面的代码是用了flask的一个扩展库,如果直接用原生的flask也可以写
from flask import Flask, request, jsonify
import numpy as np
import pandas as pd
from pickle import load
app = Flask(__name__)
model = load(open('model.pickle','rb'))
from flask import Flask, request,json
app = Flask(__name__)
@app.route('/model', methods = ['POST'])
def api_message():
if request.headers['Content-Type'] == 'application/json':
res = pd.DataFrame(request.json,index=[0]) # df
res = model.predict(res) # array
res = res.tolist()[0] # str
res = {'Species':res} # dict
return jsonify(res)
else:
return "415 Unsupported Media Type ;)"
if __name__ == '__main__':
app.run(debug=True)
最后在shell中执行curl测试,那么将是输入json,输出json了
curl -H "Content-type: application/json" -X POST http://127.0.0.1:5000/model -d '{"Sepal_Length":4.9,"Sepal_Width":3,"Petal_Length":1.4,"Petal_Width":0.2}'
想法不错,可以试试
回复删除try it
回复删除