FastAPI 返回 BERT 模型结果和指标

问题描述

我有使用 BERT 的情感分析模型,我想通过 FastAPI 获得预测文本的结果,但它总是给出否定的答案(我认为这是因为预测没有给出预测结果)。

这是我的代码

import uvicorn
from fastapi import FastAPI
import joblib

# models
sentiment_model = open("sentiment-analysis-model.pkl","rb")
sentiment_clf = joblib.load(sentiment_model)

# init app
app = FastAPI()

# Routes
@app.get('/')
async def index():
    return {"text": "Hello World! huehue"}

@app.get('/predict/{text}')
async def predict(text):
    prediction,raw_outputs = sentiment_clf.predict(text)
    if prediction == 0:
        result = "neutral"
    elif prediction == 1:
        result = "positive"
    else:
        result = "negative"
    return{"text": text,"prediction":result}

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

我还想打印准确率、F1 分数等。

我正在使用这个模型

from simpletransformers.classification import ClassificationModel

model = ClassificationModel('bert','bert-base-multilingual-uncased',num_labels=3,use_cuda=False,args={'reprocess_input_data': True,'overwrite_output_dir': True,'num_train_epochs': 1},weight=[3,0.5,1])

解决方法

您正在使用 Path parameter 构造。这意味着要调用您的 API 端点,您需要执行这样的调用:http://localhost:8000/predict/some_text。问题是 some_text 在您的案例中包含空格。除了将显式的 HTML 空间内容(例如 %20)(我不确定这是否可行)之外,这将无法注册空间,您将只拥有第一个单词。

相反,您最好使用 Request body 构造。所以是 POST 而不是 GET。像这样:

from pydantic import BaseModel


class Text(BaseModel):
    text: str


app = FastAPI()


@app.post("/predict/")
async def predict(text: Text):
    text = text.text
    ...