在 FastAPI 应用程序中将 JSON 转换为 DataFrame
Converting JSON into a DataFrame within FastAPI app
我正在尝试为银行的客户流失创建 API。我已经完成了模型,现在想使用 FastAPI 创建 API。我的问题是将 JSON 传递的数据转换为数据帧,以便能够 运行 通过模型。这是代码。
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from pycaret.classification import *
import pandas as pd
import uvicorn # ASGI
import pickle
import pydantic
from pydantic import BaseModel
class customer_input(BaseModel):
CLIENTNUM:int
Customer_Age:int
Gender:str
Dependent_count:int
Education_Level:str
Marital_Status:str
Income_Category:str
Card_Category:str
Months_on_book:int
Total_Relationship_Count:int
Months_Inactive_12_mon:int
Contacts_Count_12_mon:int
Credit_Limit:float
Total_Revolving_Bal:int
Avg_Open_To_Buy:float
Total_Amt_Chng_Q4_Q1:float
Total_Trans_Amt:int
Total_Trans_Ct:int
Total_Ct_Chng_Q4_Q1:float
Avg_Utilization_Ratio:float
app = FastAPI()
#Loading the saved model from pycaret
model = load_model('BankChurnersCatboostModel25thDec2020')
origins = [
'*'
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=['GET','POST'],
allow_headers=['Content-Type','application/xml','application/json'],
)
@app.get("/")
def index():
return {"Nothing to see here"}
@app.post("/predict")
def predict(data: customer_input):
# Convert input data into a dictionary
data = data.dict()
# Convert the dictionary into a dataframe
my_data = pd.DataFrame([data])
# Predicting using pycaret
prediction = predict_model(model, my_data)
return prediction
# Only use below 2 lines when testing on localhost -- remove when deploying
if __name__ == '__main__':
uvicorn.run(app, host='127.0.0.1', port=8000)
当我对此进行测试时,我从 OpenAPI 界面收到内部服务器错误,因此我检查了我的 cmd,错误显示
ValueError: [TypeError("'numpy.int64' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]
如何才能将传递到预测函数的数据成功转换为数据帧。谢谢。
好的,所以我通过更改 customer_input
class 解决了这个问题。我将任何 int
类型更改为 float
并修复了它。我不明白为什么。谁能解释一下?
从根本上说,这些 int
值只是一个整数,因为它们都是离散值(即选择银行中的受抚养人数量),但我想我可以在前端施加约束。
我正在尝试为银行的客户流失创建 API。我已经完成了模型,现在想使用 FastAPI 创建 API。我的问题是将 JSON 传递的数据转换为数据帧,以便能够 运行 通过模型。这是代码。
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from pycaret.classification import *
import pandas as pd
import uvicorn # ASGI
import pickle
import pydantic
from pydantic import BaseModel
class customer_input(BaseModel):
CLIENTNUM:int
Customer_Age:int
Gender:str
Dependent_count:int
Education_Level:str
Marital_Status:str
Income_Category:str
Card_Category:str
Months_on_book:int
Total_Relationship_Count:int
Months_Inactive_12_mon:int
Contacts_Count_12_mon:int
Credit_Limit:float
Total_Revolving_Bal:int
Avg_Open_To_Buy:float
Total_Amt_Chng_Q4_Q1:float
Total_Trans_Amt:int
Total_Trans_Ct:int
Total_Ct_Chng_Q4_Q1:float
Avg_Utilization_Ratio:float
app = FastAPI()
#Loading the saved model from pycaret
model = load_model('BankChurnersCatboostModel25thDec2020')
origins = [
'*'
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=['GET','POST'],
allow_headers=['Content-Type','application/xml','application/json'],
)
@app.get("/")
def index():
return {"Nothing to see here"}
@app.post("/predict")
def predict(data: customer_input):
# Convert input data into a dictionary
data = data.dict()
# Convert the dictionary into a dataframe
my_data = pd.DataFrame([data])
# Predicting using pycaret
prediction = predict_model(model, my_data)
return prediction
# Only use below 2 lines when testing on localhost -- remove when deploying
if __name__ == '__main__':
uvicorn.run(app, host='127.0.0.1', port=8000)
当我对此进行测试时,我从 OpenAPI 界面收到内部服务器错误,因此我检查了我的 cmd,错误显示
ValueError: [TypeError("'numpy.int64' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]
如何才能将传递到预测函数的数据成功转换为数据帧。谢谢。
好的,所以我通过更改 customer_input
class 解决了这个问题。我将任何 int
类型更改为 float
并修复了它。我不明白为什么。谁能解释一下?
从根本上说,这些 int
值只是一个整数,因为它们都是离散值(即选择银行中的受抚养人数量),但我想我可以在前端施加约束。