在 FastAPI 中使用机器学习时出现“TypeError:float() 参数必须是字符串或数字,而不是‘PatientAttendance’”

问题描述 投票:0回答:1

我目前正在使用 FastAPI 构建 API 来部署我的逻辑回归模型。由于某种原因,当我测试模型时,我在服务器文档中收到上述错误。

我的代码如下:

app = FastAPI()

class PatientAttendance(BaseModel):
    apptslotduration: int
    patientage: int
    log_distance: float
    pct_appts_missed: float
    doc_no_show_rate: float
    zip_no_show_rate: float
    note_no_show_rate: float
    type_no_show_rate: float
    spec_type_no_show_rate: float
    monthly_no_show_rate: float
    seasonal_no_show_rate: float
    dow_no_show_rate: float
    clinic_no_show_rate: float
    lead_time_in_days: int
    groupedstarttime: int
    priminsurance_no_show_rate: float
    secondinsurance_no_show_rate: float

@app.post('/predict/')
def predict(features: PatientAttendance):
    data = features
    prediction = model.predict([[data]])
    if prediction[0] == 0:
        result = "Patient Show"
    else:
        result = "No-Show"
    probability = model.predict_proba([[data]])

    return {
        'prediction': prediction,
        'probability': probability
    }

if __name__ == '__main__':
    uvicorn.run(app, host="127.0.0.1", port=8000)

错误:

TypeError: float() argument must be a string or a number, not 'PatientAttendance'

我正在使用 Pydantic BaseModel,我不知道为什么会收到此错误。我相信我的应用程序指向了服务器的正确方向。我尝试过使用

GET
POST
features
是我的数据集中的特征数组,我将其标准化并转换为字典。所有特征都已矢量化。每当我在服务器文档中测试我的 API 时,我似乎总是会遇到某种类型的错误。

python machine-learning fastapi predict
1个回答
0
投票

选项1

# Getting prediction
prediction = model.predict([[data.apptslotduration, data.patientage, data.pct_appts_missed, data.doc_no_show_rate, ...]])[0]

# Getting probability
probability = model.predict_proba([[data.apptslotduration, data.patientage, data.pct_appts_missed, data.doc_no_show_rate, ...]])

选项2

使用

__dict__
方法获取模型中所有属性的值:

# Getting prediction
prediction = model.predict([list(data.__dict__.values())])[0]

# Getting probability
probability = model.predict_proba([list(data.__dict__.values())])

或者(更好)使用 Pydantic 的

.dict()
方法(在 Pydantic V2 中
.dict()
.model_dump()
取代):

# Getting prediction
prediction = model.predict([list(data.dict().values())])[0]

# Getting probability
probability = model.predict_proba([list(data.dict().values())])

选项3

使用

.dict()
方法将输入数据(来自 Pydantic 模型)转换为字典(在 Pydantic V2 中
.dict()
.model_dump()
取代),然后转换为 Pandas 数据框:

import pandas as pd

# Converting input data into Pandas DataFrame
df = pd.DataFrame([data.dict()])

# Getting prediction
prediction = model.predict(df)[0]

# Getting probability
probability = model.predict_proba(df)

更多选择

如果您有

list
的输入,请查看 此答案(选项 3)。

© www.soinside.com 2019 - 2024. All rights reserved.