如何使用 FastAPI 部署 NLP 模型?

模型部署是将训练好的自然语言处理模型集成到生产环境中的过程。模型接收输入数据,预测输出。

有多种将 NLP 模型部署到生产环境的方法,包括 Flask、Django、Bottle 等框架。

本文将分享使用 FastAPI 构建和部署 NLP 模型。

在本文中,你将学习:

  • 如何构建一个基于 IMDB 电影评论的 NLP 模型
  • 什么是 FastAPI 以及如何安装它
  • 如何使用 FastAPI 部署模型
  • 如何在任何 Python 应用程序中使用已部署的 NLP 模型。

构建 NLP 模型

首先,我们将构建我们的 NLP 模型。我们将使用 IMDB 电影评论数据集创建一个简单的模型,该模型可以将评论分类为积极或消极。

以下是步骤:

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, classification_report, plot_confusion_matrix
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from string import punctuation
from nltk.tokenize import word_tokenize
import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import re  # 正则表达式
warnings.filterwarnings("ignore")
np.random.seed(123)

加载数据集

data = pd.read_csv("../data/labeledTrainData.tsv", sep='\t')
data.head()

此代码从数据文件夹加载IMDB电影评论数据集,并使用head()方法显示前五行。

分析数据集

我们现在将探索数据集以了解其结构和特征。

# 检查数据形状
data.shape

# 识别缺失值
data.isnull().sum()

# 评估类别分布
data.sentiment.value_counts()

数据预处理

文本数据通常包含不必要的字符,需要在输入机器学习模型之前进行清理。我们将使用NLTK删除停用词、数字、标点符号,并将单词词形还原(转换为其基本形式)。

stop_words = stopwords.words('english')

def text_cleaning(text, remove_stop_words=True, lemmatize_words=True):
    # 清理文本
    text = re.sub(r"[^A-Za-z0-9]", " ", text)
    text = re.sub(r"\'s", " ", text)
    text = re.sub(r'http\S+', ' link ', text)
    text = re.sub(r'\b\d+(?:\.\d+)?\s+', '', text)  # 移除数字
    text = ''.join([c for c in text if c not in punctuation])
    
    # 移除停用词(可选)
    if remove_stop_words:
        text = text.split()
        text = [w for w in text if not w in stop_words]
        text = " ".join(text)
    
    # 词形还原(可选)
    if lemmatize_words:
        text = text.split()
        lemmatizer = WordNetLemmatizer()
        lemmatized_words = [lemmatizer.lemmatize(word) for word in text]
        text = " ".join(lemmatized_words)
    
    return text

data["cleaned_review"] = data["review"].apply(text_cleaning)

# 拆分特征和目标变量
X = data["cleaned_review"]
y = data.sentiment.values

# 将数据分为训练集和测试集
X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.15, random_state=42, shuffle=True, stratify=y)

构建 NLP 模型

我们将训练一个多项式朴素贝叶斯算法来将评论分类为积极或消极。

在训练之前,我们需要使用 TfidfVectorizer 将清理过的文本评论转换为数值特征。

TfidfVectorizer 将文本文档集合转换为 TF-IDF 特征矩阵,这些特征表示单词在文档中的重要性相对于整个语料库。

# 创建分类管道
sentiment_classifier = Pipeline(steps=[
    ('pre_processing', TfidfVectorizer(lowercase=False)),
    ('naive_bayes', MultinomialNB())
])

# 训练情感分类器
sentiment_classifier.fit(X_train, y_train)

# 在验证数据上测试模型性能
y_preds = sentiment_classifier.predict(X_valid)
accuracy_score(y_valid, y_preds)

保存模型管道

我们将使用joblib库保存训练好的模型管道。

import joblib
joblib.dump(sentiment_classifier, '../models/sentiment_model_pipeline.pkl')

什么是 FastAPI?

FastAPI 是一个用于构建 Python API 的高性能、现代Web框架。

它提供了自动交互文档和比其他框架更简便的编码特性。

FastAPI构建于两个核心Python库之上:Starlette(用于Web处理)和Pydantic(用于数据处理和验证)。

如何安装 FastAPI

确保您具有最新版本的FastAPI,运行以下命令:

pip install fastapi

您还需要一个 ASGI 服务器用于生产环境,如uvicorn:

pip install uvicorn

使用 FastAPI 部署 NLP 模型

我们现在将使用FastAPI将训练好的NLP模型部署为RESTful API。

创建一个新的 Python 文件

创建一个名为main.py的文件来存放 FastAPI 应用程序代码。

导入包

from string import punctuation
from nltk.tokenize import word_tokenize
import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import re
import os
from os.path import dirname, join, realpath
import joblib
import uvicorn
from fastapi import FastAPI

初始化 FastAPI 应用实例

app = FastAPI(
    title="Sentiment Model API",
    description="一个使用NLP模型预测电影评论情感的简单API",
    version="0.1",
)

加载NLP模型

with open(join(dirname(realpath(__file__)), "models/sentiment_model_pipeline.pkl"), "rb") as f:
    model = joblib.load(f)

定义清理数据的函数

我们将重用第一部分中的 text_cleaning 函数来清理新的评论。

def text_cleaning(text, remove_stop_words=True, lemmatize_words=True):
    # ...(参考前面的代码块)
    return text

创建预测端点

API端点是系统之间通信的入口。在这里,我们将定义一个名为/predict-review的端点,它接受GET请求。

@app.get("/predict-review")
def predict_sentiment(review: str):
    """
    接收评论并预测其情感的函数。
    :param review: 评论文本。
    :return: 包含预测情感和概率的字典。
    """
    cleaned_review = text_cleaning(review)
    prediction = model.predict([cleaned_review])
    output = int(prediction[0])
    probas = model.predict_proba([cleaned_review])
    output_probability = "{:.2f}".format(float(probas[:, output]))
    sentiments = {0: "消极", 1: "积极"}
    result = {"prediction": sentiments[output], "Probability": output_probability}
    return result

运行API

使用以下命令运行FastAPI应用程序:

uvicorn main:app --reload

--reload标志允许代码更改时自动重启服务器。

如何使用已部署的 NLP 模型

FastAPI 为你的API提供自动交互文档。在浏览器中访问http://localhost:8000/docs即可访问此界面。此界面允许您直接测试API端点。

以下是如何使用/predict-review端点的方法:

  1. 访问http://localhost:8000/docs
  2. 点击/predict-review端点。
  3. 在“review”字段中输入电影评论文本。
  4. 点击“Execute”按钮。

API将返回一个包含预测情感(积极或消极)和相关概率分数的JSON响应。

参考资料

  • 14
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值