为sklearn模型服务的烧瓶衍生包装器
skserve的Python项目详细描述
skserve-一个用于部署sklearn模型的flaskapi包装器
由Adam Grbac创建。
这个包使用Flask创建一个简单的框架来部署在scikitlearn中创建的现有机器学习模型,并通过restfulapi公开它们。在
这个包的主要对象是ModelServer类,它是Flask类的一个子类,因此可以像普通Flask服务器实例一样进行处理和定制。在
用法
基本
要使用这个包,首先创建一个scikit学习模型(或者一个模型类型,它具有与sklearn相似的predict/predict_proba API)。在
训练模型后,使用joblib模块中的dump()函数将模型保存为文件。在
一个你有一个你想要部署的模型文件,例如一个简单的逻辑回归模型,有7个输入-logreg.模型,以下代码是基本部署的示例:
from skserve import ModelServer
from joblib import load
model = load('logreg.model')
app = ModelServer(model=model)
if __name__ == "__main__":
app.run()
此代码将在127.0.0.1:5000上启动Flask API,路径如下:
- “/”:服务器的根目录将返回一个小的欢迎消息,可用于测试连接。在
- “/help”:帮助将包和提供给API的文档(即输入数据字典)和存在于预处理/后处理函数中的任何docstring进行路由。在
- “/predict”:predict路由通过发送POST请求调用正在部署的模型的predict方法。请求应该包含数据作为一个JSON对象,具有特性名称和值。在
- “/predict_proba”:predict_proba路由通过发送POST请求调用正在部署的模型的predict_proba方法。请求应该包含数据作为一个JSON对象,具有特性名称和值。在
为了从模型中请求预测,我们向/predict路由发送一个POST请求,其中包含7个必需字段:
^{pr2}$高级
ModelServer类也可以使用其他参数初始化:
- pre:一个预处理函数,它接受POST请求传递的数据的pandas数据帧,并返回模型可以接受的类似数据帧。在
- post:一个后处理函数,它接受模型评分的结果(一个列表),并将作为JSON对象的“scores”元素返回,作为对发起post请求的响应。在
- 数据字典:将特征名称映射到特征描述的词典。此字典用作/help路由的一部分(用于用户信息)以及为模型排序数据(因此POST数据不需要按顺序排列)。在
也可以通过将主机和端口参数传递给run()函数来更改服务器的主机和端口。在
下面是对基本功能的上述扩展的示例:
from skserve import ModelServer
from joblib import load
model = load('logreg.model')
data_dict = {"Pclass":"Passenger Class",
"Age":"Passenger Age",
"Fare":"Fare Paid",
"Parch":"Parents / Children",
"SibSp":"Siblings",
"Sex":"Gender Code - 0: Male - 1: Female"}
def pre_process(data):
"""Pre-Processor:
This should show up on the help page.
The function changes the string into a Binary value."""
data["Sex"] = data["Sex"].apply(lambda x: 0 if x == "male" else 1)
return data
def post_process(data):
"""Post-Processer:
This should also show up on the help page.
This function takes the scores, and shifts from 0 <-> 1 to -1 <-> 1"""
return(data*2 - 1)
app = ModelServer(model=model,
pre=pre_process,
post=post_process,
data_dict=data_dict)
if __name__ == "__main__":
app.run(host='0.0.0.0',port=1337)
这些更改也会对/help路由上返回的页面产生影响,例如:
SSSSS K K SSSSS EEEEE RRRRR V V EEEEE
S K K S E R R V V E
SSSSS KKK SSSSS EEEEE RRRRR V V EEEEE
S K K S E R RR V V E
SSSSS K K SSSSS EEEEE R R V EEEEE
This model API can be used to predict outputs (Regression + Classification) or probabilities (Classification).
These are accessed by sending a POST request to <host>/predict or <host>/predict_proba respectively.
The input data should be a JSON object with the following fields:
Pclass: Passenger Class
Age: Passenger Age
Fare: Fare Paid
Parch: Parents / Children
SibSp: Siblings
Sex: Gender Code - 0: Male - 1: Female
The data sent will be pre-processed using a pre-defined function:
Pre-Processor:
This should show up on the help page
The model results will be post-processed using a pre-defined function:
Post-Processer:
This should also show up on the help page
- 项目
标签: