r/FastAPI • u/According-Promise-23 • Apr 14 '22
Question Using Pydantic models (Basemodel) for model.predict using FastAPI (Python) getting error "value is not a valid dict"
I'm trying to use Pydantic models with FastAPI to make return multiple predictions (for a list of inputs), the problem is we can't use Pydantic models directly to model.predict function, so I converted it to a dictionary, I'm getting an error I get an error "value is not a valid dict" trying :
from fastapi
import FastAPI
import uvicorn
from pydantic import BaseModel
import pandas as pd
from typing import List
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)
0
Apr 14 '22
[deleted]
0
u/According-Promise-23 Apr 14 '22
"So to fix it you should say input_list.dict(). You can load that list straight into a data frame since all the dicts have the same keys. It will have a row for each dict." when I arrive here model.predict does not work taking a dict in each row and return error TypeError: float() argument must be a string or a number, not 'dict' u/Not-the-best-name
3
u/Remote_Cancel_7977 Apr 15 '22 edited Apr 15 '22
What is your current request body? The request json should looks like below:
and I think this line is incorrect
input_list.inputsis alistnot adictin your pydantic model definition.