I'm trying to use Pydantic
models with FastAPI to make multiple predictions (for a list of inputs). The problem is that one can't pass Pydantic models directly to model.predict()
function, so I converted it to a dictionary, however, I'm getting the following error:
AttributeError: 'list' object has no attribute 'dict'
My code:
from fastapi import FastAPI
import uvicorn
from pydantic import BaseModel
import pandas as pd
from typing import List
app = FastAPI()
class Inputs(BaseModel):
id: int
f1: float
f2: float
f3: str
class InputsList(BaseModel):
inputs: List[Inputs]
@app.post('/predict')
def predict(input_list: InputsList):
df = pd.DataFrame(input_list.inputs.dict())
prediction = classifier.predict(df.loc[:, df.columns != 'id'])
probability = classifier.predict_proba(df.loc[:, df.columns != 'id'])
return {'id': df["id"].tolist(), 'prediction': prediction.tolist(), 'probability': probability.tolist()}
I have also a problem with the return, I need the output to be something like :
[
{
"id": 123,
"prediction": "class1",
"probability": 0.89
},
{
"id": 456,
"prediction": "class3",
"probability": 0.45
}
]
PS: the id
in Inputs
class doesn't take place in the prediction (is not a feature), but I need it to be shown next to its prediction (to reference it).