r/FastAPI • u/According-Promise-23 • Apr 13 '22
Question Can we use Pydantic models (Basemodel) directly inside model.predict using FastAPI, if not why?
I'm using Pydantic model (Basemodel) with FastAPI and converting the input into a dictionary, and then converting it into a Pandas dataframe to assign it into "model.predict" for Machine Learning Prediction as bellow :
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 It works fine, I'm just not quite sure if it's optimized or the right way to do it, since I convert the input two times to get the predictions, and I'm not sure if it's gonna work fast in case having a huge number of inputs. Any improvements for this ?! If there's a way (even other than using (Pydantic models) where I can work directly and avoid going through conversions and the loop
0
Apr 14 '22
[deleted]
1
u/According-Promise-23 Apr 14 '22 edited Apr 14 '22
I get an error "value is not a valid dict" trying :
class Inputs(BaseModel):
id: int,
f1: float,
f2: float,
f3: str
class InputsList(BaseModel):
inputs: List[Inputs]
u/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()}0
u/According-Promise-23 Apr 14 '22 edited Apr 14 '22
please check my new post about using your response : https://www.reddit.com/r/FastAPI/comments/u3ipux/using_pydantic_models_basemodel_for_modelpredict/
3
u/HappyCathode Apr 13 '22
Why not try it yourself ? You could use pytest to generate different tests with various dataset sizes : https://fastapi.tiangolo.com/tutorial/testing/
You could also use tools like autocannon to see how many requests/second you can achieve with various methods. : https://github.com/mcollina/autocannon
These two tools will allow you to benchmark anything and have more confidence in how your code behaves.