框架 flask
example
1.sklearn 训练模型并保持
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.utils import check_random_state
from sklearn.externals import joblib
n = 100
x = np.arange(n)
rs = check_random_state(0)
y = rs.randint(-50, 50, size=(n,)) + 50. * np.log1p(np.arange(n))
lr = LinearRegression()
lr.fit(x[:, np.newaxis], y)
joblib.dump(lr,'lr_model.pkl')
2.训练好的模型提供远程服务
import numpy as np
from flask import Flask
from flask import request
from flask import jsonify
from sklearn.externals import joblib
#导入模型
model = joblib.load('lr_model.pkl')
app = Flask(__name__)
@app.route('/',methods=['POST','GET'])
def output_data():
text=request.args.get('inputdata')
if text:
temp = [float(x) for x in text.split(',')]
temp = np.array(temp).reshape((1, -1))
ouputdata = model.predict(temp)
return jsonify(str(ouputdata[0]))
if __name__ == '__main__':
app.config['JSON_AS_ASCII'] = False
app.run(host='0.0.0.0',port=5003) # 127.0.0.1 #指的是本地ip,0,0,0,0指支持远程访问
print('运行结束')
3.测试
test.py
import requests
base = 'http://127.0.0.1:5003/?inputdata=5' #ip地址换成启动服务的机器地址
response = requests.get(base)
answer = response.json()
print('预测结果',answer)