掘金 人工智能 08月10日
【Hugging Face实战】创建一个情感分析应用
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文详细介绍了如何基于Hugging Face平台,利用Gradio快速搭建一个中文情感分析应用。文章首先回顾了Hugging Face的系列教程,然后重点讲解了如何创建Gradio应用模板,并逐步构建了情感分析的用户界面,包括文本输入、情感结果输出和示例文本展示。在核心逻辑实现部分,文章详细阐述了如何加载预训练的BERT模型和分词器,并训练了一个用于情感分类的自定义模型,最后通过绑定Gradio按钮事件,完成了整个情感分析应用的搭建与测试,支持正向和负向两种情感判断。

📝 **应用搭建与界面设计**:文章指导用户在Hugging Face上创建Gradio应用模板,并展示了如何使用Gradio构建一个直观的用户界面。界面设计包含文本输入框、分析按钮、清空按钮以及结果展示区域,同时提供了示例文本方便用户快速体验,整体布局清晰,易于操作。

🧠 **情感分析模型构建**:核心技术在于加载预训练的中文BERT模型(bert-base-chinese)和对应的分词器。通过定义一个包含BERT特征提取和全连接层的自定义模型,并加载训练好的参数(/params/1bert.pt),实现了对输入文本进行情感分析的功能。模型被设置为eval模式以保证稳定性。

⚙️ **情感分析流程实现**:通过`collate_fn`函数对输入文本进行编码和预处理,包括分词、填充和转换为PyTorch张量。`analyze_sentiment`函数接收文本输入,调用模型进行预测,并输出分析结果(正向/负向评价)和情感分类标签。该函数被绑定到Gradio界面的按钮和输入事件上,实现了交互式的情感分析。

🧪 **应用测试与局限性**:文章展示了启动服务后的实际运行效果,并通过示例文本进行了测试。需要注意的是,该模型目前仅支持正向和负向两种情感分类,不支持中性评价的判断。

前言

前面介绍了Hugging Face平台及核心API的使用方式,今天尝试在前面预训练模型的基础上搭建 一个情感分析应用,对往期内容感兴趣的小伙伴也可以看往期:

创建Space应用

首先在Hugging Face上创建一个Gradio模版应用,详细创建流程可以查看之前这篇文章:
【Hugging Face】Hugging Face Space空间的基本使用方式

创建完成后将项目克隆到本地,我们将拥有一个类似的项目结构:

搭建情感分析应用

搭建情感分析应用UI

使用Gradio搭建情感分析应用,提供 分析内容、分析结果、示例 等相关参数配置

def create_interface():    """    创建Gradio界面    """    with gr.Blocks(title="情感分析应用", theme=gr.themes.Soft()) as demo:        gr.Markdown("# 🎭 情感分析应用")        gr.Markdown("输入文本,AI将分析其情感倾向")        with gr.Row():            with gr.Column(scale=2):                # 输入区域                text_input = gr.Textbox(                    label="输入要分析的文本",                    placeholder="请输入您想要分析情感的文本...",                    lines=4,                    max_lines=10                )                # 按钮                with gr.Row():                    analyze_btn = gr.Button("🔍 分析情感", variant="primary")                    clear_btn = gr.Button("🗑️ 清空", variant="secondary")            with gr.Column(scale=2):                # 输出区域                result_summary = gr.Textbox(                    label="分析结果",                    lines=3,                    interactive=False                )                # 情感标签显示                sentiment_label = gr.Label(                    label="情感分类",                )        # 示例文本        gr.Markdown("### 📝 示例文本")        examples = gr.Examples(            examples=[                ["这个产品真的很棒,我非常满意!"],                ["服务态度太差了,完全不推荐"],                ["还可以吧,没什么特别的感觉"],                ["质量很好,物流也很快,五星好评!"],                ["价格太贵了,性价比不高"]            ],            inputs=text_input,            cache_examples=False        )    return demo

整体界面布局结构如下:

运行 python man.py 启动服务,在浏览器中打开效果如下

情感分析逻辑实现

加载 模型、分词器 以及 训练的模型参数,注意需要将模型切换到 eval 模式(使用 *.pt 模型需要将模型切换到 eval 模式否则会报错)

import gradio as grimport torchimport torch.nn as nnfrom transformers import BertTokenizer, BertModeldevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")names = ['负向''正向']# 分词器tokenizer = BertTokenizer.from_pretrained("bert-base-chinese")class Model(nn.Module):    def __init__(self, bert_model):        super().__init__()        self.bert = bert_model        # 全连接,模型输入为768,分类为2        self.fc = nn.Linear(7682)    #    def forward(self, input_ids, attention_mask, token_type_ids):        # 使用预训练模型提取特征, 上游任务不参与训练,锁定权重        with torch.no_grad():            # Correctly call the BertModel instance stored in self.bert            output = self.bert(input_ids, attention_mask, token_type_ids)        # 下游参与训练,二分类任务,获取最新后的状态        output = self.fc(output.last_hidden_state[:, 0])        # softmax激活函数,NV结构,获取特征值dim维度为1        output = output.softmax(dim=1)        return output# 加载预训练模型bert_model = BertModel.from_pretrained("ckiplab/bert-base-chinese").to(device)model = Model(bert_model).to(device)model.load_state_dict(torch.load("/params/1bert.pt"))# 切换到eval模式model.eval()def collate_fn(data):    sentes = []    sentes.append(data)    #编码    data = tokenizer.batch_encode_plus(        batch_text_or_text_pairs=sentes,        truncation=True,        padding="max_length",        max_length=350,        return_tensors="pt",        return_length=True    )    input_ids = data["input_ids"]    attention_mask = data["attention_mask"]    token_type_ids = data["token_type_ids"]    return input_ids, attention_mask, token_type_ids

创建一个函数 analyze_sentiment 用于接收和处理Gradio传递的参数

def analyze_sentiment(text):    """    对文本进行情感分析    """    input_ids, attention_mask, token_type_ids = collate_fn(text)    input_ids = input_ids.to(device)    attention_mask = attention_mask.to(device)    token_type_ids = token_type_ids.to(device)    # 上游不参与训练    with torch.no_grad():        out = model(input_ids, attention_mask, token_type_ids)    # 找到每个样本在指定维度上的最大值的索引    out = out.argmax(dim=1)    return f"{names[out]}评价", names[out]

为Gradio按钮绑定事件

def create_interface():    """    创建Gradio界面    """    with gr.Blocks(title="情感分析应用", theme=gr.themes.Soft()) as demo:        gr.Markdown("# 🎭 情感分析应用")        gr.Markdown("输入文本,AI将分析其情感倾向")        with gr.Row():            with gr.Column(scale=2):                # 输入区域                text_input = gr.Textbox(                    label="输入要分析的文本",                    placeholder="请输入您想要分析情感的文本...",                    lines=4,                    max_lines=10                )                # 按钮                with gr.Row():                    analyze_btn = gr.Button("🔍 分析情感", variant="primary")                    clear_btn = gr.Button("🗑️ 清空", variant="secondary")            with gr.Column(scale=2):                # 输出区域                result_summary = gr.Textbox(                    label="分析结果",                    lines=3,                    interactive=False                )                # 情感标签显示                sentiment_label = gr.Label(                    label="情感分类",                )        # 示例文本        gr.Markdown("### 📝 示例文本")        examples = gr.Examples(            examples=[                ["这个产品真的很棒,我非常满意!"],                ["服务态度太差了,完全不推荐"],                ["还可以吧,没什么特别的感觉"],                ["质量很好,物流也很快,五星好评!"],                ["价格太贵了,性价比不高"]            ],            inputs=text_input,            outputs=[result_summary, sentiment_label],            fn=analyze_sentiment,            cache_examples=False        )        # 绑定事件        analyze_btn.click(            fn=analyze_sentiment,            inputs=text_input,            outputs=[result_summary, sentiment_label]        )        clear_btn.click(            fn=lambda: (""""""),            outputs=[text_input, result_summary, sentiment_label]        )        # 回车键触发分析        text_input.submit(            fn=analyze_sentiment,            inputs=text_input,            outputs=[result_summary, sentiment_label]        )    return demo

重新运行服务,进行测试,该模型只有正向和负向评价,不支持中性评价

在线体验

在线体验地址:huggingface.co/spaces/zhou…

友情提示

见原文:【Hugging Face实战】创建一个情感分析应用

本文同步自微信公众号 "程序员小溪" ,这里只是同步,想看及时消息请移步我的公众号,不定时更新我的学习经验。

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

Hugging Face Gradio 情感分析 BERT 自然语言处理
相关文章