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

前言

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

创建Space应用

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

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

搭建情感分析应用

搭建情感分析应用UI

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

ini 复制代码
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 模式否则会报错)

ini 复制代码
import gradio as gr
import torch
import torch.nn as nn
from transformers import BertTokenizer, BertModel
device = 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(768, 2)
    #
    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传递的参数

python 复制代码
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按钮绑定事件

ini 复制代码
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实战】创建一个情感分析应用

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

相关推荐
墨风如雪2 小时前
OpenAI 甩出王炸:GPT-5.2-Codex 上线,这次它想做你的“赛博合伙人”
aigc
智界前沿7 小时前
集之互动AI创意视频解决方案:商业级可控,让品牌创意从“灵感”直达“落地”
人工智能·aigc
chuntian_tester10 小时前
Qwen通义千问大模型
测试工具·aigc
Java后端的Ai之路10 小时前
【分析式AI】-过拟合(含生活案例说明)
人工智能·aigc·生活·过拟合·分析式ai
imbackneverdie13 小时前
AI工具如何重塑综述写作新体验
数据库·人工智能·考研·自然语言处理·aigc·论文·ai写作
阿杰学AI15 小时前
AI核心知识57——大语言模型之MoE(简洁且通俗易懂版)
人工智能·ai·语言模型·aigc·ai-native·moe·混合专家模型
用户479492835691515 小时前
拆包、立边界、可发布:Gemini CLI 的 Monorepo 设计我学到了什么
aigc·agent·ai编程
程序员X小鹿15 小时前
一句话生科普动画视频的AI工具来了,3分钟搞定教学动画!算法演示、科学原理....(附实测案例)
aigc
好汉学技术16 小时前
TensorFlow/Keras模型优化教程:从提升精度到降低部署成本(实战版)
aigc