问题描述
@H_404_0@我将pycaret用作我的ML工作流程,我尝试使用FastAPI创建API。这是我第一次进入生产级别,所以我对API有点困惑
@H_404_0@我有10个功能;年龄:浮动,live_province:str,live_city:str,live_area_big:str,live_area_small:str,性别:浮动,婚姻:浮动,银行:str,薪水:浮动,金额:浮动和包含二进制值(0的标签和1)。
@H_404_0@这是我构建API的脚本
from pydantic import BaseModel
import numpy as np
from pycaret.classification import *
import uvicorn
from fastapi import FastAPI
app = 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: float
input_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
@H_404_0@当我尝试运行uvicorn script:app
并转到文档时,找不到适合我的功能的参数,该参数仅显示模型和input_dict
this Wikipeda article
@H_404_0@如何将我的功能带到API中的参数上?
解决方法
您的问题出在API函数的定义上。您为数据输入添加了一个参数,但没有告诉FastAPI它的类型。 另外,我假设您不是要使用全局加载的模型,而不会使用它作为参数。同样,您也不需要为输入数据创建全局实例,因为您想从用户那里获取它。
因此,只需将函数的签名更改为:
def predict(input_dict: Data):
并删除该行:
input_dict = Data
(这将为您的课程Data
创建一个别名,名为input_dict
)
您最终会得到:
app = 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: float
@app.post("/predict")
def predict(input_dict: Data):
predictions_df = predict_model(estimator=model,data=input_dict)
predictions = predictions_df['Score'][0]
return predictions
此外,我建议将类Data
的名称更改为更清晰易懂的名称,即使我认为DataUnit
也会更好,因为Data
太笼统了。
您需要键入Pydantic模型以使其与FastAPI一起使用
想象一下,当您需要记录该函数时,您真的在使用标准Python,
def some_function(price: int) ->int:
return price
使用 Pydantic ,与上面的示例没有什么不同
您的class Data
实际上是具有强大功能的Python @dataclass
(来自Pydantic)
from fastapi import Depends
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: 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 ,您将得到一个查询,例如分别定义每个字段时。