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

人工智能例子汇总: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. 预测

    • 使用训练好的模型对新的句子进行情感预测。
相关推荐
青瓷程序设计10 分钟前
【交通标志识别系统】python+深度学习+算法模型+Resnet算法+人工智能+2026计算机毕设项目
人工智能·python·深度学习
Mr.huang12 分钟前
RNN系列模型演进及其解决的问题
人工智能·rnn·lstm
智驱力人工智能16 分钟前
货车走快车道检测 高速公路安全治理的工程实践与价值闭环 高速公路货车占用小客车道抓拍系统 城市快速路货车违规占道AI识别
人工智能·opencv·算法·安全·yolo·目标检测·边缘计算
老百姓懂点AI20 分钟前
[RAG架构] 拒绝向量检索幻觉:智能体来了(西南总部)AI agent指挥官的GraphRAG实战与AI调度官的混合索引策略
人工智能·架构
ws20190721 分钟前
技术迭代与湾区赋能:AUTO TECH China 2026广州汽车零部件展的四大核心价值
人工智能·科技·汽车
啥都想学点25 分钟前
关于制作技术视频讲解的问卷调查
python
喵手25 分钟前
Python爬虫实战:博物馆官网的“展览预告/正在热展”栏目,抓取展览名称、精确展期、具体展厅位置以及票务/预约规则(附CSV导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·博物馆信息采集·采集展览预告/正在热展等·采集数据csv导出
喵手26 分钟前
Python爬虫实战:电商实体消歧完整实战 - 从混乱店铺名到标准化知识库的工程化实现,一文带你搞定!
爬虫·python·算法·爬虫实战·零基础python爬虫教学·同名实体消除·从混乱店铺名到标准化知识库
源于花海28 分钟前
迁移学习简明手册——迁移学习相关资源汇总
人工智能·机器学习·迁移学习
aihuangwu30 分钟前
deepseek图表怎么导出
人工智能·ai·deepseek·ds随心转