是否存在通过函数调用sklearn模型的更有效方法?尝试使用它为其余的api调用部署api端点
我希望我的输出为{prediction: "...", "class_0_proba": "...", "class_1_proba": "..."}
作为字典/ json模式结构。
此外,如何修改函数以允许多个json / dict行? ...目前我的代码只能接受1个示例行进行测试
我当前正在使用json.dumps()
,然后使用json.loads()
将字符串转换回字典。这似乎不是最好的方法。
from sklearn.externals import joblib
import numpy as np
import pandas as pd
# sklearn classification model
model = joblib.load("model.pkl")
import json
# function
def preds(dict):
df = pd.DataFrame([dict])
result = model.predict(df)
class_0_p= model.predict_proba(df)[0][0]
class_1_p= model.predict_proba(df)[0][1]
j = json.dumps({"prediction": result[0],
"class0_prob": class_0_p,
"class1_prob": class_1_p})
j = json.loads(j)
return j
# testing function on sample observation
preds({
"c1": "raw text as a feature",
"c2": "another raw text col as a feature",
"c3": 0,
"c4": 0,
"c5": 0,
"c6": "text value",
"c7": "some text value",
"c8": "flag",
"c9": "another flag",
"c10": 0,
"c11": 0,
"c12": 0,
"c13": 0
})
# output from function
{'prediction': 'class_0_label',
'class0_prob': 0.6784582619132933,
'class1_prob': 0.3215417380867065}