情感分析Baseline

一、情感分析Baseline:

IMDb数据集包含50000条电影评论,每条评论都标记为正面或负面评论

数据集下载:http://ai.stanford.edu/~amaas/data/sentiment/

本次主要学习情感分析简单模型,选择RNN模型做Baseline。

RNN每次的输入为一个单词序列:X={x1,...,xT}X={x1,...,xT},并为每个输入单词输出一个隐向量:h。

二、对IMDB电影评论进行情感分析

TorchText 的主要概念之一是Field,这些定义了应如何处理数据。 我们的数据集为带标签数据集,即数据由评论的原始字符串和情感组成,“pos”表示积极情绪,“neg”表示消极情绪。

数据预处理

import torch
from torchtext.legacy import data
# 设置随机种子数,该数可以保证随机数是可重复的
SEED = 1234
# 设置种子
torch.manual_seed(SEED)
torch.backends.deterministic = True
# 读取数据和标签
TEXT = data.Field(tokenize = 'spacy', tokenizer_language = 'en_core_web_sm')
LABEL = data.LabelField(dtype = torch.float)
from torchtext.legacy import datasets
# 以下代码自动下载IMDb数据集并将其拆分为规范的训练集和测击集,
# 作为torchtext.datasets对象。它使用我们之前定义的Frields处理数据。IMDb数据集包含50000条电影评论,每条评论都标记为正面或负面评论。
train_data, test_data = datasets.IMDB.splits(TEXT, LABEL)
# 查看我们的训练集和测试集大小
print(f'Number of training examples: {len(train_data)}')
print(f'Number of testing examples: {len(test_data)}')
# Number of training examples: 25000
# Number of testing examples: 25000
# 查看一下示例数据
print(vars(train_data.examples[0]))
# {'text': ['elvira', 'mistress', 'of', 'the', 'dark', 'is', 'one', 'of', 'my', 'fav', 'movies', ',', 'it', 'has', 'every', 'thing', 'you', 'would', 'want', 'in', 'a', 'film', ',', 'like', 'great', 'one', 'liners', ',', 'sexy', 'star', 'and', 'a', 'Outrageous', 'story', '!', 'if', 'you', 'have', 'not', 'seen', 'it', ',', 'you', 'are', 'missing', 'out', 'on', 'one', 'of', 'the', 'greatest', 'films', 'made', '.', 'i', 'ca', "n't", 'wait', 'till', 'her', 'new', 'movie', 'comes', 'out', '!'], 'label': 'pos'}

构建模型

import torch.nn as nn

训练模型

SGD随机梯度下降计算

猜你喜欢

转载自blog.csdn.net/qq_36816848/article/details/120317443