部署sklearn模型

保存模型

# 切分训练集和数据集
data_train, data_test, target_train, target_test = train_test_split(
    housing.data, housing.target, test_size=0.1, random_state=0)

# 构建决策树
dtr = tree.DecisionTreeRegressor(random_state=0)
dtr.fit(data_train, target_train)

# 查看score
score = dtr.score(data_test, target_test)
print("score=", score)
print(data_train[:1])

# 保存模型
dump(dtr, model_file_name)

加载模型

global dtr
dtr = load(model_file_name)
result = dtr.predict([[8.3252, 41., 6.98412698, 1.02380952, 322., 2.55555556, 37.88, 122.23]])
print(result)

部署模型

@app.route("/predict", methods=["POST"])
def predict():
    if dtr:
        try:
            json_ = request.json

            prediction = list(dtr.predict(json_["instances"]))
            return jsonify({"prediction": prediction})
        except Exception as e:
            return jsonify({'error': str(e), 'trace': traceback.format_exc()})
    else:
        print('train first')
        return 'no model here'

请求参数

post调用

参考资料