pytorch实现简单的情感分析算法

news/2025/2/2 20:15:14 标签: pytorch, 人工智能, python

 人工智能例子汇总:AI常见的算法和例子-CSDN博客 

在PyTorch中实现中文情感分析算法通常涉及以下几个步骤:数据预处理、模型定义、训练和评估。下面是一个简单的实现示例,使用LSTM模型进行中文情感分析。

1. 数据预处理

首先,我们需要对中文文本进行分词,并将文本转换为数值形式(如词向量)。可以使用jieba进行分词,并使用torchtext或自定义的词汇表将词语转换为索引。

import torch
import torch.nn as nn
import torch.optim as optim
from torchtext.vocab import build_vocab_from_iterator
from torchtext.data.utils import get_tokenizer
import jieba

# 示例数据
data = [
    ("我非常喜欢这个电影", "positive"),
    ("这个电影太糟糕了", "negative"),
    ("这部电影真的很棒", "positive"),
    ("我不喜欢这个电影", "negative"),
    ("这部电影让我感动", "positive"),
    ("这部电影太无聊了", "negative"),
    ("演员表演非常出色", "positive"),
    ("剧情太差了", "negative"),
    ("画面非常精美", "positive"),
    ("完全不值得看", "negative")
]


# 分词函数
def tokenize(text):
    return list(jieba.cut(text))


# 构建词汇表
tokenizer = get_tokenizer(tokenize)
vocab = build_vocab_from_iterator(map(tokenizer, [text for text, label in data]), specials=["<unk>"])
vocab.set_default_index(vocab["<unk>"])


# 将文本转换为索引
def text_to_indices(text):
    return [vocab[token] for token in tokenizer(text)]


# 将标签转换为数值
label_to_index = {"positive": 1, "negative": 0}

# 预处理数据
processed_data = [(text_to_indices(text), label_to_index[label]) for text, label in data]


# 定义LSTM模型
class LSTMModel(nn.Module):
    def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim, n_layers, bidirectional, dropout):
        super(LSTMModel, self).__init__()
        self.embedding = nn.Embedding(vocab_size, embedding_dim)
        self.lstm = nn.LSTM(embedding_dim, hidden_dim, num_layers=n_layers, bidirectional=bidirectional,
                            dropout=dropout)
        self.fc = nn.Linear(hidden_dim * 2 if bidirectional else hidden_dim, output_dim)
        self.dropout = nn.Dropout(dropout)

    def forward(self, text):
        embedded = self.dropout(self.embedding(text))  # [sequence_length, batch_size, embedding_dim]
        output, (hidden, cell) = self.lstm(embedded)
        hidden = self.dropout(torch.cat((hidden[-2, :, :], hidden[-1, :, :]), dim=1))  # [batch_size, hidden_dim * 2]
        return self.fc(hidden)  # [batch_size, output_dim]


# 超参数
VOCAB_SIZE = len(vocab)
EMBEDDING_DIM = 100
HIDDEN_DIM = 256
OUTPUT_DIM = 1
N_LAYERS = 2
BIDIRECTIONAL = True
DROPOUT = 0.5

# 初始化模型
model = LSTMModel(VOCAB_SIZE, EMBEDDING_DIM, HIDDEN_DIM, OUTPUT_DIM, N_LAYERS, BIDIRECTIONAL, DROPOUT)

# 损失函数和优化器
criterion = nn.BCEWithLogitsLoss()
optimizer = optim.Adam(model.parameters())


# 训练函数
def train(model, data, optimizer, criterion, epochs=10):
    model.train()
    for epoch in range(epochs):
        total_loss = 0
        for text, label in data:
            text = torch.tensor(text).unsqueeze(1)  # [sequence_length, batch_size=1]
            label = torch.tensor([label], dtype=torch.float32)  # [batch_size=1]

            optimizer.zero_grad()
            predictions = model(text).squeeze(0)  # [batch_size=1]
            loss = criterion(predictions, label)
            loss.backward()
            optimizer.step()

            total_loss += loss.item()

        print(f'Epoch: {epoch + 1}, Loss: {total_loss / len(data)}')


# 训练模型
train(model, processed_data, optimizer, criterion, epochs=20)


# 预测函数
def predict_sentiment(model, sentence):
    model.eval()
    with torch.no_grad():
        text = torch.tensor(text_to_indices(sentence)).unsqueeze(1)  # [sequence_length, batch_size=1]
        prediction = torch.sigmoid(model(text).squeeze(0))  # [batch_size=1]
        return "positive" if prediction.item() > 0.5 else "negative"


# 测试模型
test_sentences = [
    "这个电影真的很棒",
    "这部电影太无聊了",
    "演员表演非常出色",
    "完全不值得看"
]

for sentence in test_sentences:
    print(f'Sentence: {sentence}, Predicted sentiment: {predict_sentiment(model, sentence)}')
  1. 数据预处理

    • 使用 jieba 对中文文本进行分词。

    • 使用 torchtext 构建词汇表,并将文本转换为索引。

    • 将标签转换为数值(positive 为1,negative 为0)。

  2. 模型定义

    • 使用 LSTM 模型进行情感分析。

    • 模型包括嵌入层、LSTM 层和全连接层。

  3. 训练

    • 使用二元交叉熵损失函数(BCEWithLogitsLoss)和 Adam 优化器。

    • 训练模型 20 个 epoch。

  4. 预测

    • 使用训练好的模型对新的句子进行情感预测。


http://www.niftyadmin.cn/n/5840269.html

相关文章

Kubernetes组成及常用命令

Pods(k8s最小操作单元)ReplicaSet & Label(k8s副本集和标签)Deployments(声明式配置)Services(服务)k8s常用命令Kubernetes(简称K8s)是一个开源的容器编排系统,用于自动化应用程序的部署、扩展和管理。自2014年发布以来,K8s迅速成为容器编排领域的行业标准,被…

【LeetCode 刷题】二叉树-公共祖先

此博客为《代码随想录》二叉树章节的学习笔记&#xff0c;主要内容为二叉树公共祖先问题相关的题目解析。 文章目录 236. 二叉树的最近公共祖先235. 二叉搜索树的最近公共祖先 236. 二叉树的最近公共祖先 题目链接 class Solution:def lowestCommonAncestor(self, root: Tre…

mac安装wireshark

mac启动wireshark时&#xff0c;提示没有权限抓包&#xff0c;报错内容如下&#xff1a; “The capture session could not be initiated on interface ‘en0’ (You don’t have permission to capture on that device). Please check to make sure you have sufficient perm…

5 个开源且免费的提示词管理系统,按照 从优到劣 排序

1. PromptSource 研发背景: 国家: 国际协作&#xff08;主要由美国和欧洲团队主导&#xff09;。 团队: BigScience Workshop&#xff0c;一个由 Hugging Face 和多个研究机构共同支持的开源社区。 简介: 专注于创建、管理和共享提示词模板。 特点: 提供 Web 界面&#xff…

Google Chrome-便携增强版[解压即用]

Google Chrome-便携增强版 链接&#xff1a;https://pan.xunlei.com/s/VOI0OyrhUx3biEbFgJyLl-Z8A1?pwdf5qa# a 特点描述 √ 无升级、便携式、绿色免安装&#xff0c;即可以覆盖更新又能解压使用&#xff01; √ 此增强版&#xff0c;支持右键解压使用 √ 加入Chrome增强…

gitlab云服务器配置

目录 1、关闭防火墙 2、安装gitlab 3、修改配置 4、查看版本 GitLab终端常用命令 5、访问 1、关闭防火墙 firewall-cmd --state 检查防火墙状态 systemctl stop firewalld.service 停止防火墙 2、安装gitlab xftp中导入安装包 [rootgitlab ~]#mkdir -p /service/tool…

WSL2中安装的ubuntu开启与关闭探讨

1. PC开机后&#xff0c;查询wsl状态 在cmd或者powersell中输入 wsl -l -vNAME STATE VERSION * Ubuntu Stopped 22. 从windows访问WSL2 wsl -l -vNAME STATE VERSION * Ubuntu Stopped 23. 在ubuntu中打开一个工作区后…

包装类(全面解析)

Java中的常用类 含义:直接调用实现一些功能【如:Arrays工具类中的方法】 主要关注常用类中的【以jdk api中的包装类为例】 A、字段摘要(一般只看全局常量,字段名是全大写即常量) B、构造方法摘要(通过看构造方法就能知道此类怎么去创建对象) C、方法摘要(一个方法…