我使用 pycaret 作为我的机器学习工作流程,我尝试使用 FastAPI 创建一个 API。这是我的第一次尝试将模型投入生产,所以我对 API 有些困惑
我有10个特征;年龄: float, 居住省份: str, 居住城市: str, 大居住区域: str, 小居住区域: str, 性别: float, 婚姻状况: float, 银行: str, 薪水: float, 金额: float,还有一个标签包含二进制值(0和1)。
这是我构建 API 的脚本
from pydantic import BaseModelimport numpy as npfrom pycaret.classification import *import uvicornfrom fastapi import FastAPIapp = FastAPI()model = load_model('catboost_cm_creditable')class Data(BaseModel): age: float live_province: str live_city: str live_area_big: str live_area_small: str sex: float marital: float bank: str salary: float amount: floatinput_dict = Data@app.post("/predict")def predict(model, input_dict): predictions_df = predict_model(estimator=model, data=input_dict) predictions = predictions_df['Score'][0] return predictions
当我尝试运行 uvicorn script:app
并查看文档时,我找不到我的特征参数,参数只显示了 model 和 input_dict
如何将我的特征添加到 API 的参数中?
回答:
你需要为你的 Pydantic 模型添加类型提示,使其与 FastAPI 兼容
想象一下,你真正在使用标准 Python,当你需要记录那个函数时,
def some_function(price: int) ->int: return price
使用 Pydantic 与上面的例子没有任何不同
你的 class Data
实际上是一个来自 Pydantic 的超级强大的 Python @dataclass
from fastapi import Dependsclass Data(BaseModel): age: float live_province: str live_city: str live_area_big: str live_area_small: str sex: float marital: float bank: str salary: float amount: float@app.post("/predict")def predict(data: Data = Depends()): predictions_df = predict_model(estimator=model, data=data) predictions = predictions_df["Score"][0] return predictions
有一个小技巧,使用 Depends,你将得到类似于单独定义每个字段的单一查询。