I would like to test my pipeline in FastAPI, but I can't find the mistake in my code. When I test it using the Visual Studio Code (using a print() statement), it works. However, when I try accessing the endpoint through the browser, I get Internal Server Error. It works when I return something else as the prediction results (e.g., some string), instead of the actual prediction results.
Here is my code:
class FraudDetection333(BaseModel):
"""
Input features validation for the ML model
"""
user_id: int
signup_day: int
signup_month: int
signup_year: int
purchase_day: int
purchase_month: int
purchase_year: int
purchase_value: float
source: str
browser: str
sex: str
age: int
@api.post("/predictions_test",tags=['DecisionTreeClassifier'])
def predictions_test(fraud:FraudDetection333):
"""
:param:input data from the post request
:return predicted type
"""
features = [[
fraud.user_id,
fraud.signup_day,
fraud.signup_month,
fraud.signup_year,
fraud.purchase_day,
fraud.purchase_month,
fraud.purchase_year,
fraud.purchase_value,
fraud.source,
fraud.browser,
fraud.sex,
fraud.age
]]
rf_model = joblib.load('./rf_model.pkl')
new = (pd.DataFrame(features, index = ['0'], columns = ['user_id','signup_day',
'signup_month', 'signup_year',
'purchase_day', 'purchase_month', 'purchase_year','purchase_value',
'source','browser','sex','age']))
new_prediction = rf_model.predict(new)
return {
"Predicted transaction(1 - fraud, 0 - not fraud)": new_prediction
}
If I try the below (using a print() statement), it prints out the expected outcome:
featuress={
"user_id": 22058,
"signup_day": 24,
"signup_month": 2,
"signup_year": 2015,
"purchase_day": 18,
"purchase_month": 4,
"purchase_year": 2015,
"purchase_value": 34,
"source": "SEO",
"browser": "Chrome",
"sex": "M",
"age": 39
}
rf_model = joblib.load('./rf_model.pkl')
new = (pd.DataFrame(featuress, index = ['0'], columns = ['user_id','signup_day',
'signup_month', 'signup_year',
'purchase_day', 'purchase_month', 'purchase_year','purchase_value',
'source','browser','sex','age']))
new_prediction = rf_model.predict(new)
print(new)
print(new_prediction)
If I type return {"Predicted transaction(1 - fraud, 0 - not fraud)": 'Hi'}, it also works.
Image here.
print()(andprint(type(...)),print(len(...)), etc.) to see which part of code is executed and what you really have in variables. It is called"print debuging"and it helps to see what code is really doing.JSONbutJSONcan send only basis data types -string,int,float,list,dict. It can't sendDataFramenornumpy.array. You have to convert it to basis data types.