我们可以使用FastApi直接在Model.predict()内部使用Pydantic Models(basemodel),如果不是,为什么?
我正在使用fastapi的pydantic模型( basemodel
),然后将输入转换为 dictionary
,然后将其转换为pandas dataframe
,为了将其传递到 model.predict()
用于机器学习预测的功能,如下所示:
from fastapi import FastAPI
import uvicorn
from pydantic import BaseModel
import pandas as pd
from typing import List
class Inputs(BaseModel):
f1: float,
f2: float,
f3: str
@app.post('/predict')
def predict(features: List[Inputs]):
output = []
# loop the list of input features
for data in features:
result = {}
# Convert data into dict() and then into a DataFrame
data = data.dict()
df = pd.DataFrame([data])
# get predictions
prediction = classifier.predict(df)[0]
# get probability
probability = classifier.predict_proba(df).max()
# assign to dictionary
result["prediction"] = prediction
result["probability"] = probability
# append dictionary to list (many outputs)
output.append(result)
return output
它可以正常工作,我不确定它是优化还是正确的方法,因为我将输入转换两次以获取预测。另外,我不确定在拥有大量输入的情况下,它是否可以正常工作 fast 。有什么改进吗?如果有一种方法(甚至除了使用Pydantic模型之外),我可以直接工作并避免进行转换和循环。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您应该为变量/对象使用更多描述性名称。例如:
您不能将pydantic模型直接传递到
predict()
函数,因为它接受数据array
而不是pydantic模型。可用选项在下面列出。选项1
您可以使用以下内容(以下
i
表示inputs
list中的项目):选项2
您可以使用 list :
或,最好是,使用pydantic的
dict()
方法(注: /17865804“>dict()
已被model_dump()
):选项3
使用pandas
dataframe
(如下)同样,在pydantic v2dict()
已被model_dump()
)替换:选项4
您可以避免通过单个项目循环并调用
predict()< /code>多次函数,通过使用以下(再次,在pydantic v2中,用
dict()
model_dump()
)替换您不想使用pandas
dataframe
):First, you should use more descriptive names for your variables/objects. For example:
You cannot pass the Pydantic model directly to the
predict()
function, as it accepts a dataarray
, not a Pydantic model. Available options are listed below.Option 1
You could use the following (The
i
below represents an item from theinputs
list):Option 2
You could use the
__dict__
method to get the values of all attributes in the model and convert them into alist
:or, preferably, use the Pydantic's
dict()
method (Note: In Pydantic V2dict()
has been replaced bymodel_dump()
):Option 3
Use a Pandas
DataFrame
as follows (again, in Pydantic V2dict()
has been replaced bymodel_dump()
):Option 4
You could avoid looping over individual items and calling the
predict()
function multiple times, by using, instead, the below (once again, in Pydantic V2, replacedict()
withmodel_dump()
):or (in case you wouldn't like using Pandas
DataFrame
):