返回顶部
热门问答 更多热门问答
技术文章 更多技术文章

如何使用 FastAPI 部署 NLP 模型?

[复制链接]
链载Ai 显示全部楼层 发表于 7 小时前 |阅读模式 打印 上一主题 下一主题

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

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

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

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

构建 NLP 模型

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

以下是步骤:

importnumpyasnp
importpandasaspd
fromsklearn.model_selectionimporttrain_test_split
fromsklearn.pipelineimportPipeline
fromsklearn.naive_bayesimportMultinomialNB
fromsklearn.metricsimportaccuracy_score,classification_report,plot_confusion_matrix
fromsklearn.feature_extraction.textimportTfidfVectorizer,CountVectorizer
fromstringimportpunctuation
fromnltk.tokenizeimportword_tokenize
importnltk
fromnltk.corpusimportstopwords
fromnltk.stemimportWordNetLemmatizer
importre#正则表达式
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')

deftext_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([cforcintextifcnotinpunctuation])

#移除停用词(可选)
ifremove_stop_words:
text=text.split()
text=[wforwintextifnotwinstop_words]
text="".join(text)

#词形还原(可选)
iflemmatize_words:
text=text.split()
lemmatizer=WordNetLemmatizer()
lemmatized_words=[lemmatizer.lemmatize(word)forwordintext]
text="".join(lemmatized_words)

returntext

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库保存训练好的模型管道。

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

什么是 FastAPI?

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

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

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

如何安装 FastAPI

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

pipinstallfastapi

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

pipinstalluvicorn

使用 FastAPI 部署 NLP 模型

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

创建一个新的 Python 文件

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

导入包

fromstringimportpunctuation
fromnltk.tokenizeimportword_tokenize
importnltk
fromnltk.corpusimportstopwords
fromnltk.stemimportWordNetLemmatizer
importre
importos
fromos.pathimportdirname,join,realpath
importjoblib
importuvicorn
fromfastapiimportFastAPI

初始化 FastAPI 应用实例

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

加载NLP模型

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

定义清理数据的函数

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

deftext_cleaning(text,remove_stop_words=True,lemmatize_words=True):
#...(参考前面的代码块)
returntext

创建预测端点

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

@app.get("/predict-review")
defpredict_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],"robability"utput_probability}
returnresult

运行API

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

uvicornmain: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响应。

- EOF-

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

链载AI是专业的生成式人工智能教程平台。提供Stable Diffusion、Midjourney AI绘画教程,Suno AI音乐生成指南,以及Runway、Pika等AI视频制作与动画生成实战案例。从提示词编写到参数调整,手把手助您从入门到精通。
  • 官方手机版

  • 微信公众号

  • 商务合作

  • Powered by Discuz! X3.5 | Copyright © 2025-2025. | 链载Ai
  • 桂ICP备2024021734号 | 营业执照 | |广西笔趣文化传媒有限公司|| QQ