我已经训练了一个信用卡流失模型,并使用joblib
保存了它。现在,我想使用FastAPI作为restful API进行部署。我已经完成了数据的预处理,如下所示,但是我得到了这个错误:
TypeError: float() argument must be a string or a number, not 'ModelMetaclass.
请看下面的代码和错误信息。谢谢。
from fastapi import FastAPI
import joblib
import uvicorn
from pydantic import BaseModel
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.compose import ColumnTransformer, make_column_selector as selector
import pandas as pd
import numpy as np
app = FastAPI(title ='Credit Card Churn Prediction', version = 1.0, description = 'Classification Machine Learning Prediction')
class model_input(BaseModel):
Customer_Age : int
Gender : int
Dependent_count : int
Education_level : int
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 : int
Total_Revolving_Bal : int
Avg_Open_To_Buy : int
Total_Amt_Chng_Q4_Q1 : int
Total_Trans_Amt : int
Total_Trans_Ct : int
Total_Ct_Chng_Q4_Q1 : int
Avg_Utilization_Ratio : int
# load the model
model = joblib.load("joblib_CC_Model.pkl")
@app.post("/credit_card_churn_prediction")
async def predicts(input:model_input):
# Numeric Features
num_features = [[input.Customer_Age, input.Dependent_count, input.months_on_book, input.Total_Relationship_Count, input.Months_Inactive_12_mon,
input.Contacts_Count_12_mon, input.Credit_Limit, input.Total_Revolving_Bal, input.Avg_Open_To_Buy, input.Total_Amt_Chng_Q4_Q1, input.Total_Trans_Amt,
input.Total_Trans_Ct, input.Total_Ct_Chng_Q4_Q1, input.Avg_Utilization_Ratio, input.Gender, input.Education_level]]
num_pipeline = Pipeline([("Scaler", StandardScaler())])
# Categorical Features
cat_features = [[input.Gender, input.Education_level, input.Marital_status, input.Card_category]]
cat_pipeline = Pipeline([("onehot", OneHotEncoder())])
final_input = ColumnTransformer(transformers = [("numeric_preprocessing", num_pipeline, num_features),
("categorical_preprocessing", cat_pipeline, cat_features)])
prediction = model.predict([[model_input]])
return prediction
if __name__ == '__main__':
uvicorn.run("Main:app", reload = True)
我已经构建了一个分类ML模型,我正在使用FastAPI部署它,但我得到这个错误:
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 419, in run_asgi
result = await app( # type: ignore[func-returns-value]
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 78, in __call__
return await self.app(scope, receive, send)
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\fastapi\applications.py", line 270, in __call__
await super().__call__(scope, receive, send)
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\starlette\applications.py", line 124, in __call__
await self.middleware_stack(scope, receive, send)
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\starlette\middleware\errors.py", line 184, in __call__
raise exc
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\starlette\middleware\errors.py", line 162, in __call__
await self.app(scope, receive, _send)
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\starlette\middleware\exceptions.py", line 79, in __call__
raise exc
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\starlette\middleware\exceptions.py", line 68, in __call__
await self.app(scope, receive, sender)
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 21, in __call__
raise e
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 18, in __call__
await self.app(scope, receive, send)
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\starlette\routing.py", line 706, in __call__
await route.handle(scope, receive, send)
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\starlette\routing.py", line 276, in handle
await self.app(scope, receive, send)
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\starlette\routing.py", line 66, in app
response = await func(request)
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\fastapi\routing.py", line 235, in app
raw_response = await run_endpoint_function(
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\fastapi\routing.py", line 161, in run_endpoint_function
return await dependant.call(**values)
File "d:\Work\Mine\Data Science\Projects\Data Science\FastAPI\Main.py", line 59, in predicts
prediction = model.predict([[model_input]])
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\xgboost\sklearn.py", line 1284, in predict
class_probs = super().predict(
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\xgboost\sklearn.py", line 897, in predict
test = DMatrix(
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\xgboost\core.py", line 506, in inner_f
return f(**kwargs)
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\xgboost\core.py", line 616, in __init__
handle, feature_names, feature_types = dispatch_data_backend(
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\xgboost\data.py", line 768, in dispatch_data_backend
return _from_list(data, missing, threads, feature_names, feature_types)
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\xgboost\data.py", line 700, in _from_list
return _from_numpy_array(array, missing, n_threads, feature_names, feature_types)
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\xgboost\data.py", line 171, in _from_numpy_array
data, _ = _ensure_np_dtype(data, data.dtype)
File "D:\Work\Mine\Data Science\Projects\Data Science\FastAPI\venv\lib\site-packages\xgboost\data.py", line 138, in _ensure_np_dtype
data = data.astype(np.float32, copy=False)
TypeError: float() argument must be a string or a number, not 'ModelMetaclass'
我让它在SwaggerUI上运行,并输入类BaseModel中显示的输入。
1条答案
按热度按时间yacmzcpb1#
该错误在代码的以下行中引发(如您提供的跟踪所示):
您正在将
BaseModel
类传递给predict()
函数,而不是您准备的final_input
对象。因此,您应该将上面的行更改为下面的行:请查看有关将ML模型与FastAPI here、here和here配合使用的相关答案,以及this、this和this答案。